• Mahesh Babu 187
  • NEWBIE
  • 55 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 16
    Questions
  • 20
    Replies
Hi Team,

I have written a trigger to insert a new contact through web to case only when a custom field on Case is checked. I have written test class for it.
But it is covering on first 2 lines. 
Please help me to increase it's code coverage.

TRIGGER

trigger CreateContactOnCaseCreation on Case (before insert, before update) {
    
    for(Case caseobj : Trigger.new){ 
       if(caseobj.Create_Contact__c) {
           if(caseobj.ContactId == null && caseobj.SuppliedEmail!=''){
            List<Contact> listContacts = [Select Id, Email From Contact Where Email =:caseobj.SuppliedEmail];
              if(listContacts.size() == 0) {
                 Contact cont = new Contact();
                 cont.LastName=caseobj.SuppliedName;
                 cont.Email=caseobj.SuppliedEmail;
                 cont.Phone=caseobj.SuppliedPhone;
                 Account account = [Select Id from Account where Name = 'Web-2-Case' limit 1];
                 cont.AccountId=account.Id;
                 insert cont;
                 caseobj.ContactId = cont.Id;
                 caseobj.Create_Contact__c = false;
              } else {
                Trigger.New[0].addError('Contact cannot be created; reason: The contact with the email address already exist in system');
                caseobj.Create_Contact__c = false;
              }
           } else {
               Trigger.New[0].addError('Contact cannot be created; reason: The criteria to create contact does not meet');
               caseobj.Create_Contact__c = false;
           }
       }
    }
}

TEST CLASS

@isTest
private class CreateContactOnCaseCreationTest {
     @isTest static void Test1(){
         Case cs = new Case();
         cs.Status = 'New';
         cs.Origin = 'Web';
         cs.SuppliedName = 'Test Test';
         cs.SuppliedPhone = '1234567890';
         cs.SuppliedEmail = 'test@test.com';
         cs.Subject = 'Test';
         cs.Create_Contact__c= false; 
         Test.startTest();
         insert cs;
         Account a = new Account();
         a.Name = 'Test';
         a.BillingCountry = 'Afghanistan';
         insert a;
         Contact con = new Contact();
         con.LastName = cs.SuppliedName;
         con.Email = cs.SuppliedEmail;
         con.Phone = cs.SuppliedPhone;
         Account account = [Select Id from Account where Name = 'Test' limit 1];
         con.AccountId = account.Id;
         insert con;
         Test.stopTest();
        // System.assertEquals(1,Contact.size());
     }
}


Thanks,
Mahesh
 
Hi Team,
I have a requirement to auto-create an account and contact through web-to-case. I am able to create contact through trigger if the email id doesn't exists.As the contact is created it becomes private conatct because it not associated to any account. So I need to create the account from 'Suppliedcompany' field and map this account to the contact.

APEX CODE

trigger CreateContact on Case (before insert) {
    
        List<String> emailAddresses = new List<String>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedEmail!='')
        {
            emailAddresses.add(caseObj.SuppliedEmail);             
        }
    }
    List<Contact> listContacts = [Select Id, Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null && caseObj.SuppliedName!=null && caseObj.SuppliedName!='' && caseObj.SuppliedEmail!=null &&
            caseObj.SuppliedEmail!='' && caseObj.SuppliedPhone!=null && caseObj.SuppliedPhone!='' && !takenEmails.contains(caseObj.SuppliedEmail))
         {
            String[] nameParts = caseObj.SuppliedName.split(' ',2);
            if (nameParts.size() == 2)
            {
             Contact cont = new Contact(FirstName=nameParts[0], LastName=nameParts[1], Email=caseObj.SuppliedEmail, Phone=caseObj.SuppliedPhone);
                emailToContactMap.put(caseObj.SuppliedEmail,cont);
                casesToUpdate.add(caseObj);
            }
        }
    }
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(caseObj.SuppliedEmail);
        caseObj.ContactId = newContact.Id;
    }
}

Thanks,
Mahesh
Hi Team,

We have a Apex class which is called in a trigger. I have writen a test class for that Apex class but my code coverage is only 5%. Only first 2 lines are getting covered. I have tried multiple approaches but all in vain. Please assist me to do the changes.

APEX CODE:

public class BQDetailsUpdateClass {

    public static void createBQDetails(Product2 product){
               if(product.Vertical__c != null && product.Vertical__c.equals('Credit Cards') && product.Approval_Status__c != null && product.Approval_Status__c.equals('Approved')) {
                List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: product.Id and Pricebook2Id != '01s41000007uZohAAE' and IsActive = true];
                for(PriceBookEntry pbe : pbes) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    if(product.Lightbox_Pricing__c) {
                        bqd.Product__c = product.Id;
                        bqd.Vantage_Pricing__c = true;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    } else {
                        bqd.Product__c = product.Id;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    }
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(pbe.BQ_Detail__c)) {
                        insert bqd;
                        pbe.BQ_Detail__c = bqd.Id;
                        update pbe;
                    } else {
                        bqd.Id = pbe.BQ_Detail__c;
                        update bqd;
                    }
                    
                }
                List<Product_Offering__c> poffers = [Select Id ,CurrencyIsoCode, Offer_Name__c ,BQ_Detail__c,List_Price__c, End_Date__c, Start_Date__c from Product_Offering__c where Product__c =: product.Id and Active__c = true];
                
                for(Product_Offering__c poffer : poffers) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    bqd.Product__c = product.Id;
                    bqd.Price__c = poffer.List_Price__c;
                    bqd.CurrencyIsoCode = poffer.CurrencyIsoCode;
                    bqd.Offer_Name__c = poffer.Offer_Name__c;
                    bqd.Start_Date__c = poffer.Start_Date__c;
                    bqd.End_Date__c = poffer.Start_Date__c;
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(poffer.BQ_Detail__c)) {
                        insert bqd;
                        poffer.BQ_Detail__c = bqd.Id;
                        update poffer;
                    } else {
                        bqd.Id = poffer.BQ_Detail__c;
                        update bqd;
                    }
                }
              }    
}

TEST CLASS:

@isTest(SeeAllData=true)
public class BQDetailsUpdateClassTest {
    
    @isTest
    public static void Test1(){
        
            Product2 prod = new Product2();
            PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd1 = new BQ_Detail__c();        
            bqd1.Product__c=prod.Id;        
            bqd1.Price__c=standardPrice.UnitPrice;
            bqd1.Vantage_Pricing__c=true;
            bqd1.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
            insert bqd1;      
       

    //PricebookEntry updatePriceBookEntry = new PricebookEntry( id = standardPrice.Id,UnitPrice = 30.00);
    //update updatePriceBookEntry;    
       
       /*public static void  test2(){
            BQ_Detail__c bqd = new BQ_Detail__c();
            Product2 prod = new Product2();
              PricebookEntry pbes = new PricebookEntry();
           bqd.Id=pbes.BQ_Detail__c;
           update bqd; 
        }*/
    
   /* @isTest
     public static void Test2(){
      Product2 prod = new Product2();
     PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd2 = new BQ_Detail__c();
        
            bqd2.Product__c=prod.Id;
        
        bqd2.Price__c=standardPrice.UnitPrice;
        bqd2.Vantage_Pricing__c=true;
        bqd2.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
        insert bqd2; 
*/              
       
       BQDetailsUpdateClass.createBQDetails(prod);
        
    } 
    
          /*Pricebook2 customPB = new Pricebook2(
          Name='Custom Pricebook',
          isActive=true);
        insert customPB;*/   
      
        /*PricebookEntry pbes = new PricebookEntry(
            Pricebook2Id = customPB.Id, 
            Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert pbes;
        
  
        List<PricebookEntry> pbes1 = [SELECT ID, Product2Id, 
        Pricebook2.isStandard, Pricebook2.isActive, isActive FROM PricebookEntry];*/   
    
        /*Id pricebookId = Test.getStandardPricebookId();
        Product2 p =new Product2();
        p.Name = 'Test';
        p.Description = 'Test';
        p.Vertical__c = 'Credit Cards';
        p.Lightbox_Pricing__c = false;
        p.Location__c = '100 - SF 760 Market St';
        p.CurrencyIsoCode='CAD - Canadian Dollar';
        insert p;
        List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: p.Id];
     PriceBookEntry pbe = new PriceBookEntry();
     pbe.UnitPrice = 5;
      pbe.Pricebook2Id = '01s02000000xDR3AAM';
     insert pbe;  
        
    }*/      
}

Thanks,
Mahesh
Hi Team,

I am stuck in a trigger. I have 2 look-up fields on Product obejct. Through first look-up field i.e  'Parent Id'  we can select Account Name and through second look-up field we select Account Manager Name. Now my requirement is as i select the Account Name in first look-up field, it should automatically populate respective Account Manager Name in second look-up field  .
I have created the trigger.

trigger AddAccountManager on Product2 (before update) {
        Set<Id> Ids = new Set<Id>();
    for(Product2 p : Trigger.new){
        Ids.add(p.Parent_ID__c);
    }
    Map<Id, Account> accountownername = new Map<Id , Account>([SELECT id, Name, AccountManager__c FROM Account WHERE Id IN: Ids]);
    for(Product2 p : Trigger.new){
        if(p.Parent_ID__c != null && accountownername.containsKey(p.Parent_ID__c))   {
            p.Account_Manager__c = accountownername.get(p.Parent_ID__c).AccountManager__c;
        }
    }
     }  

I am getting this error:

Apex trigger AddAccountManager caused an unexpected exception, contact your administrator: AddAccountManager: execution of AfterUpdate caused by: System.FinalException: Record is read-only: ()

Please help me to solve this.

Thanks,
Mahesh
I have a requirement to create a new record of a custom object. This custom object should be populated with List Price field value of Standard Price Object. I was trying to create it with Process Builder. But process builder doesn't have option of Standard Price Object in add object section. Please help me what approach needs to be followed.
If it can be done through trigger, please share a sample code.

Thanks,
Mahesh
I have three objects A, B and C . I want to create new record of obj. A having name field value from obj. B and price field value from obj. C. A and B are child object of B but C doesn't have any relation with A. 

1. If it is possible through flow.Can anyone share the steps.
2. If it is possible through trigger. Please share a sample code.

Thanks,
Mahesh
Hi Team,

I have a requirement to create new records for a custom object in Salesforce.
My conditions are:
1. On my Product Object, there is a picklist field 'Verticals' and a     checkbox field 'Pricing'. Now if the value of Picklist field is 'A' and checkbox is unchecked, then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Product Offering which is a related list on Product Object. 

2.  On my Product Object, there is a picklist field 'Verticals'. Now if the value of Picklist field is 'B', then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Block Prices which is a related list on Product Object.

Can anyone tell how this can we created?
Hi Team,

I have a requirement where I have an external website outside Salesforce.The customer fills out a form on this website and also adds attachment in the form. On submit of this form, I want a new case object record to be created in salesforce with customer filled data.The attachment should be visible to the agent who will work on the case and also the agent should get notified when an attachment is added in the form. Any help would be appreciated.

Thanks in Advance,
Mahesh
I have written a Apex class which is getting called in a trigger. Now I have written a test class for the Apex class. But my code coverage is 0%.

APEX CLASS

public class ChangeOwnerClass{

    public static void changeOwner(Quote quote){
        
        Opportunity opp = [Select ID, CreatedById, OwnerId from Opportunity where Id =: quote.OpportunityId];
        System.debug(opp.OwnerId);
        if(opp.OwnerId != null) {}
            User user = [Select Id,ProfileId from User where Id=: opp.OwnerId];
            System.debug(user.Id);
            if(user!= null && user.ProfileId != null) {
                Profile profile = [Select name from Profile where Id =: user.ProfileId ];
                System.debug(profile.name);
                if(profile !=null && profile.name != null && profile.name == 'TriLink Sales & Service') {
                    quote.ownerId = opp.CreatedById;
                }            
            }
        }
    }

TRIGGER

trigger ChangeOwner on Quote (before insert) {
    
        for(Quote q: Trigger.new)
        {
            ChangeOwnerClass.changeOwner(q);
        }        
    }

TEST CLASS

@isTest
public class ChangeOwnerTest {

    @isTest static void changeOwnerTest(){
        Opportunity opp = new Opportunity();
        opp.Name = 'Test';
        opp.LeadSource = 'Test';
        opp.StageName = 'Identification';
        opp.CloseDate = Date.newInstance(2020, 12, 14);
        opp.OwnerId = '0056A00000264YcQAI';
        insert opp;
        if(opp.OwnerId != null) {}
        User user = [Select Id,ProfileId from User where Id=: opp.OwnerId];
        if(user!= null && user.ProfileId != null){
            Profile profile = [Select name from Profile where Id =: user.ProfileId ];
            if(profile !=null && profile.name != null && profile.name == 'TriLink Sales & Service'){
                Quote q = new Quote();
                q.Id = opp.Id;
                q.ownerId = opp.CreatedById;
                insert q;
            }
        }
    }
}

Please help me to modify it to get the code coverage.
I have written an Apex class for changing the Quote owner as the Opportunity owner for a Profile named 'TriLink Sales & Service'. I have called this class in Trigger. But it is not updating anything.

APEX CODE:
public class changeOwnerClass{
public list<Opportunity> lstOpp = [Select id, name, ownerId from Opportunity] ;
public void changeOwner(list<Quote> lstQuote){
Profile p = [select id,Name from Profile where id=:Userinfo.getProfileid()];
System.debug(p);
for (Opportunity opp : lstOpp){
for(Quote objQuote : lstQuote){
if(p.Name == 'TriLink Sales & Service' && p.Name!= 'TriLink GMP'){
objQuote.OwnerId = opp.OwnerId;
System.debug(opp.OwnerId);
System.debug(objQuote.OwnerId);
}} } }
}

TRIGGER:
trigger changeOwner on Quote (before insert) {
changeOwnerClass clsChangeOwner = new changeOwnerClass ();
if(trigger.isInsert && trigger.isBefore){ clsChangeOwner.changeOwner(trigger.new);
} }

I can see that the opportunity owner id is not coming here. But how to get opportunity owner id here.
Please help me to solve this error.
Hi Team,

Please help to write a test class for a after delete trigger.

TRIGGER

trigger MaketheCheckboxUnused on Order_Line_Item_Serials__c (after delete) {
     //Serial_Number__c    
    List<Serial_Number__c> snumlist = New List<Serial_Number__c>();
    List<Id> orderitemlist = New List<Id>();
    For(Order_Line_Item_Serials__c oli : Trigger.Old){
        orderitemlist.add(oli.Serial_Number__c);
    }
    List<Serial_Number__c> Olis = 
        [Select Id, Name,Serial_Number__c,  
         Product__r.Id,Status__c
         From Serial_Number__c Where
         Status__c = TRUE AND
         ID IN : orderitemlist];
    
    For(Order_Line_Item_Serials__c orim : Trigger.Old){
        For(Serial_Number__c olisn : Olis){
            If(Trigger.IsDelete){
                olisn.Status__c = FALSE;
                snumlist.add(olisn);
            }
        }
    }
    update snumlist; 
}

Thanks in Advance,
Mahesh


 
Hi Team,
I have written a wrapper class contaning the search functionality. But I can't understand how to write it's test class.

APEX CODE 

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    // public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    Public map<id,Serial_Number__c> smap = new map<id,Serial_Number__c>();
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
    
    //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
    // ApexPages.addMessage(myMsg);
    
    Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        SerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
      OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
       OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
       loadSerials();
    }
    //adding page reference of the current page
  /*  public PageReference step1() {
        loadSerials();
          if(SerialList==null){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
'Please select the serial number'));

        return Page.fetchserials;
    }*/
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c,Bin_Number__c,Location__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        system.debug('Serialx' +SerialList );
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            //counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id) // && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                 //     mahesh   fetchseriallist.add(new wrapperfetch(sn,item));
                 fetchseriallist.add(new wrapperfetch(sn));
                 SelectedSerialList.add(sn);
                 //counter = counter +1; 
                }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
try{
if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
ApexPages.addMessages(myMsg);
// Code for sending Email
}
============*/
        }
    }
    
    public void search(){
        finalSearchValue = '%' + fullname + '%';
       System.debug(finalSearchValue);
        fetchseriallist = new list<wrapperfetch>();
        List<Serial_Number__c> serialList =  [Select Id, Serial_Number__c, Product_Name__c, Status__c, Bin_Number__c, Location__c FROM Serial_Number__c
                                  where Serial_Number__c like :finalSearchValue];
            System.debug(serialList.size());
        for(Serial_Number__c s : serialList){
                                      System.debug(s);
                                      fetchseriallist.add(new wrapperfetch(s));    
                                      System.debug(s);
                                  }
        
    }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public String locatn{get;set;}
        Public String binNo{get;set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        //    Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
        Public wrapperfetch(Serial_Number__c sn){  
            //this.selected=check;
            //    this.Oitem= Oi;
            //    this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.locatn=sn.Location__c;
            this.binNo=sn.Bin_Number__c;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
        }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                serials.Location__c=st.locatn;
                serials.Bin_Number__c = st.binNo;
                SelectedSerialList.add(serials);
                smap.put(serials.id,serials );
                
            }
            
        }
        if (insertordersn.size() > 0){    
                insert insertordersn;    
              //  update smap.values();    
            }
        return Page.fetchserials;    
    }       
}

Please help me to write test class for this code.

Thanks,
Mahesh
Hi Team,

I am trying to display all search results in a wrapper class, but there's this error showing up every time I save the controller:

Error: Constructor not defined: [fetchserials.wrapperfetch].<Constructor>(Serial_Number__c)

The error points to this line of code:  serialNumbers.add(new wrapperfetch(a));

APEX CLASS

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
   //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
// ApexPages.addMessage(myMsg);
       Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
        OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
        OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
        loadSerials();
    }
    //adding page reference of the current page
    public PageReference step1() {
        loadSerials();
      /*  if(SerialList==null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
                                                           'Please select the serial number'));
        } */
        return Page.fetchserials;
    }
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                    fetchseriallist.add(new wrapperfetch(sn,item));
                    SelectedSerialList.add(sn);
                    counter = counter +1; }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
            try{
                if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
    ApexPages.addMessages(myMsg);
    // Code for sending Email
}
            ============*/
        }
    }
    
    public pagereference Search()
    {
        String finalSearchValue = '%' + fullname + '%';
        serialNumbers = [Select Id, Serial_Number__c, Product_Name__c, Status__c FROM Serial_Number__c
                    where Name like :finalSearchValue];
        fetchseriallist = new list<wrapperfetch>();  
        for(Serial_Number__c a: serialNumbers)
        {
            serialNumbers.add(new wrapperfetch(a));
        }
       return null;
   }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
            //this.selected=check;
            this.Oitem= Oi;
            this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
            }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                SelectedSerialList.add(serials);
            }
            if(SelectedSerialList == NULL){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
                                                           'Please select the serial number'));
            }
        }
        insert  insertordersn;
        update SelectedSerialList;
        PageReference orderpage = new PageReference('/'+OrderID);
        orderpage.setRedirect(true);
        orderpage.getParameters().put('myId', OrderID);
        return orderpage;
       
    }
}
-----------------------------------

VISUALFORCE Page

<apex:page controller="fetchserials" lightningstylesheets="true" readonly="true">
    <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
     return false;
  }  
  </script>
<Apex:form >
<apex:pageBlock >
<apex:pageMessages id="showmsg"></apex:pageMessages>
    <apex:pageBlock>
        <apex:inputText value="{!fullname}" html-placeholder="Search" />
        <apex:commandButton value="search" action="{!Search}" />
    </apex:pageBlock>
  <apex:pageBlockTable value="{!fetchseriallist }" var="u"  style="width:100%">
    
  <apex:column headerValue="Select" > 
                        <Apex:inputcheckbox value="{!u.Selected}"  /> 
                    </apex:column>  
                    <apex:column headerValue="Serial Number" > 
                        <Apex:outputText value="{!u.serialno }"   /> 
                    </apex:column> 
                   <apex:column headerValue="Product Name" > 
                        <Apex:outputText value="{!u.prodname }"  /> 
                    </apex:column> 
                    <apex:column headerValue="Status" > 
                       <Apex:outputText value="{!u.status}"   />
                    </apex:column> 
  </apex:pageBlockTable>                  
  <apex:commandButton value="Add to Order" action="{!AddSerailNumbertoOrder}" style="margin-top: -2pt;" rerender="showmsg"/>
  <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true" id="cancel"/>

</apex:pageBlock>
  </Apex:form>
</apex:page>

Please help me to solve this issue.
Hi Team,

I am new to integration. I need to send PDF files from Salesforce to Netsuite when a checkbox is selected in Salesforce. I just know the approach that I need to convert the pdf to xml format in a restlet. But how to do this. 

Thanks in Advance 
Hi Team,

How to update child record's checkbox field value on parent record deletion using Lightning flow or trigger?
Hi, I got a question. If we upload data from a .csv file through data loader which has 500 rows and due to some error my data is uploaded till 100th row. Now I want to  upload my data from 101st row without again inserting from the starting. How could I do it?
Hi Team,

I am new to integration. I need to send PDF files from Salesforce to Netsuite when a checkbox is selected in Salesforce. I just know the approach that I need to convert the pdf to xml format in a restlet. But how to do this. 

Thanks in Advance 
Hi Team,

I have written a trigger to insert a new contact through web to case only when a custom field on Case is checked. I have written test class for it.
But it is covering on first 2 lines. 
Please help me to increase it's code coverage.

TRIGGER

trigger CreateContactOnCaseCreation on Case (before insert, before update) {
    
    for(Case caseobj : Trigger.new){ 
       if(caseobj.Create_Contact__c) {
           if(caseobj.ContactId == null && caseobj.SuppliedEmail!=''){
            List<Contact> listContacts = [Select Id, Email From Contact Where Email =:caseobj.SuppliedEmail];
              if(listContacts.size() == 0) {
                 Contact cont = new Contact();
                 cont.LastName=caseobj.SuppliedName;
                 cont.Email=caseobj.SuppliedEmail;
                 cont.Phone=caseobj.SuppliedPhone;
                 Account account = [Select Id from Account where Name = 'Web-2-Case' limit 1];
                 cont.AccountId=account.Id;
                 insert cont;
                 caseobj.ContactId = cont.Id;
                 caseobj.Create_Contact__c = false;
              } else {
                Trigger.New[0].addError('Contact cannot be created; reason: The contact with the email address already exist in system');
                caseobj.Create_Contact__c = false;
              }
           } else {
               Trigger.New[0].addError('Contact cannot be created; reason: The criteria to create contact does not meet');
               caseobj.Create_Contact__c = false;
           }
       }
    }
}

TEST CLASS

@isTest
private class CreateContactOnCaseCreationTest {
     @isTest static void Test1(){
         Case cs = new Case();
         cs.Status = 'New';
         cs.Origin = 'Web';
         cs.SuppliedName = 'Test Test';
         cs.SuppliedPhone = '1234567890';
         cs.SuppliedEmail = 'test@test.com';
         cs.Subject = 'Test';
         cs.Create_Contact__c= false; 
         Test.startTest();
         insert cs;
         Account a = new Account();
         a.Name = 'Test';
         a.BillingCountry = 'Afghanistan';
         insert a;
         Contact con = new Contact();
         con.LastName = cs.SuppliedName;
         con.Email = cs.SuppliedEmail;
         con.Phone = cs.SuppliedPhone;
         Account account = [Select Id from Account where Name = 'Test' limit 1];
         con.AccountId = account.Id;
         insert con;
         Test.stopTest();
        // System.assertEquals(1,Contact.size());
     }
}


Thanks,
Mahesh
 
Hi Team,

We have a Apex class which is called in a trigger. I have writen a test class for that Apex class but my code coverage is only 5%. Only first 2 lines are getting covered. I have tried multiple approaches but all in vain. Please assist me to do the changes.

APEX CODE:

public class BQDetailsUpdateClass {

    public static void createBQDetails(Product2 product){
               if(product.Vertical__c != null && product.Vertical__c.equals('Credit Cards') && product.Approval_Status__c != null && product.Approval_Status__c.equals('Approved')) {
                List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: product.Id and Pricebook2Id != '01s41000007uZohAAE' and IsActive = true];
                for(PriceBookEntry pbe : pbes) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    if(product.Lightbox_Pricing__c) {
                        bqd.Product__c = product.Id;
                        bqd.Vantage_Pricing__c = true;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    } else {
                        bqd.Product__c = product.Id;
                        bqd.Price__c = pbe.UnitPrice;
                        bqd.CurrencyIsoCode = pbe.CurrencyIsoCode;
                    }
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(pbe.BQ_Detail__c)) {
                        insert bqd;
                        pbe.BQ_Detail__c = bqd.Id;
                        update pbe;
                    } else {
                        bqd.Id = pbe.BQ_Detail__c;
                        update bqd;
                    }
                    
                }
                List<Product_Offering__c> poffers = [Select Id ,CurrencyIsoCode, Offer_Name__c ,BQ_Detail__c,List_Price__c, End_Date__c, Start_Date__c from Product_Offering__c where Product__c =: product.Id and Active__c = true];
                
                for(Product_Offering__c poffer : poffers) {
                    BQ_Detail__c bqd = new BQ_Detail__c();
                    bqd.Product__c = product.Id;
                    bqd.Price__c = poffer.List_Price__c;
                    bqd.CurrencyIsoCode = poffer.CurrencyIsoCode;
                    bqd.Offer_Name__c = poffer.Offer_Name__c;
                    bqd.Start_Date__c = poffer.Start_Date__c;
                    bqd.End_Date__c = poffer.Start_Date__c;
                    bqd.Eligible_for_BQ__c = true;
                    if(String.IsBlank(poffer.BQ_Detail__c)) {
                        insert bqd;
                        poffer.BQ_Detail__c = bqd.Id;
                        update poffer;
                    } else {
                        bqd.Id = poffer.BQ_Detail__c;
                        update bqd;
                    }
                }
              }    
}

TEST CLASS:

@isTest(SeeAllData=true)
public class BQDetailsUpdateClassTest {
    
    @isTest
    public static void Test1(){
        
            Product2 prod = new Product2();
            PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd1 = new BQ_Detail__c();        
            bqd1.Product__c=prod.Id;        
            bqd1.Price__c=standardPrice.UnitPrice;
            bqd1.Vantage_Pricing__c=true;
            bqd1.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
            insert bqd1;      
       

    //PricebookEntry updatePriceBookEntry = new PricebookEntry( id = standardPrice.Id,UnitPrice = 30.00);
    //update updatePriceBookEntry;    
       
       /*public static void  test2(){
            BQ_Detail__c bqd = new BQ_Detail__c();
            Product2 prod = new Product2();
              PricebookEntry pbes = new PricebookEntry();
           bqd.Id=pbes.BQ_Detail__c;
           update bqd; 
        }*/
    
   /* @isTest
     public static void Test2(){
      Product2 prod = new Product2();
     PricebookEntry standardPrice = new PricebookEntry();
            BQ_Detail__c bqd2 = new BQ_Detail__c();
        
            bqd2.Product__c=prod.Id;
        
        bqd2.Price__c=standardPrice.UnitPrice;
        bqd2.Vantage_Pricing__c=true;
        bqd2.CurrencyIsoCode=standardPrice.CurrencyIsoCode;
        insert bqd2; 
*/              
       
       BQDetailsUpdateClass.createBQDetails(prod);
        
    } 
    
          /*Pricebook2 customPB = new Pricebook2(
          Name='Custom Pricebook',
          isActive=true);
        insert customPB;*/   
      
        /*PricebookEntry pbes = new PricebookEntry(
            Pricebook2Id = customPB.Id, 
            Product2Id = prod.Id,
            UnitPrice = 12000, IsActive = true);
        insert pbes;
        
  
        List<PricebookEntry> pbes1 = [SELECT ID, Product2Id, 
        Pricebook2.isStandard, Pricebook2.isActive, isActive FROM PricebookEntry];*/   
    
        /*Id pricebookId = Test.getStandardPricebookId();
        Product2 p =new Product2();
        p.Name = 'Test';
        p.Description = 'Test';
        p.Vertical__c = 'Credit Cards';
        p.Lightbox_Pricing__c = false;
        p.Location__c = '100 - SF 760 Market St';
        p.CurrencyIsoCode='CAD - Canadian Dollar';
        insert p;
        List<PriceBookEntry> pbes = [Select Id,UnitPrice,CurrencyIsoCode,BQ_Detail__c from PriceBookEntry where Product2Id =: p.Id];
     PriceBookEntry pbe = new PriceBookEntry();
     pbe.UnitPrice = 5;
      pbe.Pricebook2Id = '01s02000000xDR3AAM';
     insert pbe;  
        
    }*/      
}

Thanks,
Mahesh
Hi Team,

I am stuck in a trigger. I have 2 look-up fields on Product obejct. Through first look-up field i.e  'Parent Id'  we can select Account Name and through second look-up field we select Account Manager Name. Now my requirement is as i select the Account Name in first look-up field, it should automatically populate respective Account Manager Name in second look-up field  .
I have created the trigger.

trigger AddAccountManager on Product2 (before update) {
        Set<Id> Ids = new Set<Id>();
    for(Product2 p : Trigger.new){
        Ids.add(p.Parent_ID__c);
    }
    Map<Id, Account> accountownername = new Map<Id , Account>([SELECT id, Name, AccountManager__c FROM Account WHERE Id IN: Ids]);
    for(Product2 p : Trigger.new){
        if(p.Parent_ID__c != null && accountownername.containsKey(p.Parent_ID__c))   {
            p.Account_Manager__c = accountownername.get(p.Parent_ID__c).AccountManager__c;
        }
    }
     }  

I am getting this error:

Apex trigger AddAccountManager caused an unexpected exception, contact your administrator: AddAccountManager: execution of AfterUpdate caused by: System.FinalException: Record is read-only: ()

Please help me to solve this.

Thanks,
Mahesh
I have a requirement to create a new record of a custom object. This custom object should be populated with List Price field value of Standard Price Object. I was trying to create it with Process Builder. But process builder doesn't have option of Standard Price Object in add object section. Please help me what approach needs to be followed.
If it can be done through trigger, please share a sample code.

Thanks,
Mahesh
I have three objects A, B and C . I want to create new record of obj. A having name field value from obj. B and price field value from obj. C. A and B are child object of B but C doesn't have any relation with A. 

1. If it is possible through flow.Can anyone share the steps.
2. If it is possible through trigger. Please share a sample code.

Thanks,
Mahesh
Hi Team,

I have a requirement to create new records for a custom object in Salesforce.
My conditions are:
1. On my Product Object, there is a picklist field 'Verticals' and a     checkbox field 'Pricing'. Now if the value of Picklist field is 'A' and checkbox is unchecked, then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Product Offering which is a related list on Product Object. 

2.  On my Product Object, there is a picklist field 'Verticals'. Now if the value of Picklist field is 'B', then it should create a new record for my custom object. That custom object should be populated with my Product name and a Price field's value. But the issue is Price field's value which needs to be populated will come from another Object named Block Prices which is a related list on Product Object.

Can anyone tell how this can we created?
Hi Team,

I have a requirement where I have an external website outside Salesforce.The customer fills out a form on this website and also adds attachment in the form. On submit of this form, I want a new case object record to be created in salesforce with customer filled data.The attachment should be visible to the agent who will work on the case and also the agent should get notified when an attachment is added in the form. Any help would be appreciated.

Thanks in Advance,
Mahesh
I have written an Apex class for changing the Quote owner as the Opportunity owner for a Profile named 'TriLink Sales & Service'. I have called this class in Trigger. But it is not updating anything.

APEX CODE:
public class changeOwnerClass{
public list<Opportunity> lstOpp = [Select id, name, ownerId from Opportunity] ;
public void changeOwner(list<Quote> lstQuote){
Profile p = [select id,Name from Profile where id=:Userinfo.getProfileid()];
System.debug(p);
for (Opportunity opp : lstOpp){
for(Quote objQuote : lstQuote){
if(p.Name == 'TriLink Sales & Service' && p.Name!= 'TriLink GMP'){
objQuote.OwnerId = opp.OwnerId;
System.debug(opp.OwnerId);
System.debug(objQuote.OwnerId);
}} } }
}

TRIGGER:
trigger changeOwner on Quote (before insert) {
changeOwnerClass clsChangeOwner = new changeOwnerClass ();
if(trigger.isInsert && trigger.isBefore){ clsChangeOwner.changeOwner(trigger.new);
} }

I can see that the opportunity owner id is not coming here. But how to get opportunity owner id here.
Please help me to solve this error.
Hi Team,

Please help to write a test class for a after delete trigger.

TRIGGER

trigger MaketheCheckboxUnused on Order_Line_Item_Serials__c (after delete) {
     //Serial_Number__c    
    List<Serial_Number__c> snumlist = New List<Serial_Number__c>();
    List<Id> orderitemlist = New List<Id>();
    For(Order_Line_Item_Serials__c oli : Trigger.Old){
        orderitemlist.add(oli.Serial_Number__c);
    }
    List<Serial_Number__c> Olis = 
        [Select Id, Name,Serial_Number__c,  
         Product__r.Id,Status__c
         From Serial_Number__c Where
         Status__c = TRUE AND
         ID IN : orderitemlist];
    
    For(Order_Line_Item_Serials__c orim : Trigger.Old){
        For(Serial_Number__c olisn : Olis){
            If(Trigger.IsDelete){
                olisn.Status__c = FALSE;
                snumlist.add(olisn);
            }
        }
    }
    update snumlist; 
}

Thanks in Advance,
Mahesh


 
Hi Team,
I have written a wrapper class contaning the search functionality. But I can't understand how to write it's test class.

APEX CODE 

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    // public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    Public map<id,Serial_Number__c> smap = new map<id,Serial_Number__c>();
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
    
    //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
    // ApexPages.addMessage(myMsg);
    
    Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        SerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
      OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
       OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
       loadSerials();
    }
    //adding page reference of the current page
  /*  public PageReference step1() {
        loadSerials();
          if(SerialList==null){
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
'Please select the serial number'));

        return Page.fetchserials;
    }*/
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c,Bin_Number__c,Location__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        system.debug('Serialx' +SerialList );
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            //counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id) // && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                 //     mahesh   fetchseriallist.add(new wrapperfetch(sn,item));
                 fetchseriallist.add(new wrapperfetch(sn));
                 SelectedSerialList.add(sn);
                 //counter = counter +1; 
                }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
try{
if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
ApexPages.addMessages(myMsg);
// Code for sending Email
}
============*/
        }
    }
    
    public void search(){
        finalSearchValue = '%' + fullname + '%';
       System.debug(finalSearchValue);
        fetchseriallist = new list<wrapperfetch>();
        List<Serial_Number__c> serialList =  [Select Id, Serial_Number__c, Product_Name__c, Status__c, Bin_Number__c, Location__c FROM Serial_Number__c
                                  where Serial_Number__c like :finalSearchValue];
            System.debug(serialList.size());
        for(Serial_Number__c s : serialList){
                                      System.debug(s);
                                      fetchseriallist.add(new wrapperfetch(s));    
                                      System.debug(s);
                                  }
        
    }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public String locatn{get;set;}
        Public String binNo{get;set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        //    Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
        Public wrapperfetch(Serial_Number__c sn){  
            //this.selected=check;
            //    this.Oitem= Oi;
            //    this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.locatn=sn.Location__c;
            this.binNo=sn.Bin_Number__c;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
        }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                serials.Location__c=st.locatn;
                serials.Bin_Number__c = st.binNo;
                SelectedSerialList.add(serials);
                smap.put(serials.id,serials );
                
            }
            
        }
        if (insertordersn.size() > 0){    
                insert insertordersn;    
              //  update smap.values();    
            }
        return Page.fetchserials;    
    }       
}

Please help me to write test class for this code.

Thanks,
Mahesh
Hi Team,

I am trying to display all search results in a wrapper class, but there's this error showing up every time I save the controller:

Error: Constructor not defined: [fetchserials.wrapperfetch].<Constructor>(Serial_Number__c)

The error points to this line of code:  serialNumbers.add(new wrapperfetch(a));

APEX CLASS

Public class fetchserials{
    
    Public string OrderID {get; set;}
    Public order OrderInstance {get; set;}
    Public List<OrderItem> OrderItemList {get; set;}
    Public Set<id> ProductIdSet {get; set;} //list to add product Ids
    Public list<Serial_Number__c> SerialList {get; set;}
    Public list<Serial_Number__c> SelectedSerialList {get; set;}
    Public Map<OrderItem,list<Serial_Number__c>> OrderVSerial{get; set;} // list to add OrderItem with their Serial Numbers
    Public List<wrapperfetch> fetchseriallist {get; set;}
    public Integer Counter;
    Public List<Order_Line_Item_Serials__c> insertordersn {get; set;} // list to add the selected orders
    public List<Serial_Number__c> serialNumbers;
    public string fullname{get;set;}
    public string finalSearchValue{get;set;}
   //ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.error,'Enter the List');
// ApexPages.addMessage(myMsg);
       Public fetchserials(){
        OrderItemList = new List<OrderItem>(); // intialize
        OrderVSerial = new Map<OrderItem,List<Serial_Number__c>>();
        fetchseriallist = new List<wrapperfetch>();
        insertordersn = new List<Order_Line_Item_Serials__c>();
        SelectedSerialList = new list<Serial_Number__c>();
        OrderID = ApexPages.currentPage().getParameters().get('Id'); //Getting the id of current order
        OrderInstance = [SELECT Id FROM Order where Id=:OrderID ];
        OrderItemList=[SELECT Id,OrderId,product2Id,PricebookEntry.Product2.Name, Quantity FROM OrderItem where OrderId =:OrderID];
        loadSerials();
    }
    //adding page reference of the current page
    public PageReference step1() {
        loadSerials();
      /*  if(SerialList==null){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
                                                           'Please select the serial number'));
        } */
        return Page.fetchserials;
    }
    
    public PageReference cancel() {
        PageReference c=new PageReference('/'+OrderID);
        return c;
    }   
    
    Public void loadSerials(){
        ProductIdSet = new set<Id>();
        For(OrderItem items :OrderItemList){
            ProductIdSet.add(items.Product2Id);// order items products add into productidset 
        }
        SerialList = [SELECT Id,Serial_Number__c,Product_Name__c ,Name,Product__c,Status__c
                      FROM Serial_Number__c where Status__c=FALSE And Product__c In:ProductIdSet limit 200 ];
        
        
        /*if(SerialList == NULL)
{
SerialList.addError('There are no values in the Serials List.'); 
}*/
        // add error exception handling
        system.debug('Serialx' +SerialList );
        For(OrderItem item :OrderItemList){
            counter = 0;
            For(Serial_Number__c sn :SerialList ){
                If( sn.Product__c == item.Product2Id && counter < item.Quantity)
                {   SelectedSerialList = new list<Serial_Number__c>();
                    fetchseriallist.add(new wrapperfetch(sn,item));
                    SelectedSerialList.add(sn);
                    counter = counter +1; }
                else{continue;}
            }
            OrderVSerial.put(item,SelectedSerialList);
            /*=====
            try{
                if(SerialList == NULL ){ ApexPages.addMessages(e); }

catch (DMLException e){
    ApexPages.addMessages(myMsg);
    // Code for sending Email
}
            ============*/
        }
    }
    
    public pagereference Search()
    {
        String finalSearchValue = '%' + fullname + '%';
        serialNumbers = [Select Id, Serial_Number__c, Product_Name__c, Status__c FROM Serial_Number__c
                    where Name like :finalSearchValue];
        fetchseriallist = new list<wrapperfetch>();  
        for(Serial_Number__c a: serialNumbers)
        {
            serialNumbers.add(new wrapperfetch(a));
        }
       return null;
   }
    
    Public class wrapperfetch{
        Public Boolean selected {get; set;}
        Public Serial_Number__c sno{get; set;}
        Public string prodname {get; set;}
        Public OrderItem Oitem{get; set;}
        Public string serialno {get; set;}
        Public Boolean status {get; set;}
        Public Id stid {get; set;}
        Public Id opid {get; set;}
        
        Public wrapperfetch(Serial_Number__c sn,OrderItem Oi){
            //this.selected=check;
            this.Oitem= Oi;
            this.opid =Oi.Id;
            this.prodname =sn.Product_Name__c;
            this.sno=sn;
            this.serialno = sn.Serial_Number__c;
            this.status=sn.status__c;
            this.stid=sn.id;
            
            }
    }
    
    Public PageReference AddSerailNumbertoOrder(){
        
        for (wrapperfetch st: fetchseriallist ){
            
            If (st.selected == true ){
                Order_Line_Item_Serials__c ordersn= new Order_Line_Item_Serials__c();
                //Order_Line_Item_Serials__c make it to true
                //make a new Order_Line_Item_Serials__c list and make it to true.
                // put that into   ordersn.Serial_Number__c=st.stid;  a new list 
                ordersn.Serial_Number__c=st.stid;
                ordersn.Order_Product__c=st.opid;
                insertordersn.add(ordersn);
                
                Serial_Number__c  serials = new Serial_Number__c();
                serials.id = st.stid;
                serials.Status__c = TRUE;
                SelectedSerialList.add(serials);
            }
            if(SelectedSerialList == NULL){
                ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Error, 
                                                           'Please select the serial number'));
            }
        }
        insert  insertordersn;
        update SelectedSerialList;
        PageReference orderpage = new PageReference('/'+OrderID);
        orderpage.setRedirect(true);
        orderpage.getParameters().put('myId', OrderID);
        return orderpage;
       
    }
}
-----------------------------------

VISUALFORCE Page

<apex:page controller="fetchserials" lightningstylesheets="true" readonly="true">
    <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
     return false;
  }  
  </script>
<Apex:form >
<apex:pageBlock >
<apex:pageMessages id="showmsg"></apex:pageMessages>
    <apex:pageBlock>
        <apex:inputText value="{!fullname}" html-placeholder="Search" />
        <apex:commandButton value="search" action="{!Search}" />
    </apex:pageBlock>
  <apex:pageBlockTable value="{!fetchseriallist }" var="u"  style="width:100%">
    
  <apex:column headerValue="Select" > 
                        <Apex:inputcheckbox value="{!u.Selected}"  /> 
                    </apex:column>  
                    <apex:column headerValue="Serial Number" > 
                        <Apex:outputText value="{!u.serialno }"   /> 
                    </apex:column> 
                   <apex:column headerValue="Product Name" > 
                        <Apex:outputText value="{!u.prodname }"  /> 
                    </apex:column> 
                    <apex:column headerValue="Status" > 
                       <Apex:outputText value="{!u.status}"   />
                    </apex:column> 
  </apex:pageBlockTable>                  
  <apex:commandButton value="Add to Order" action="{!AddSerailNumbertoOrder}" style="margin-top: -2pt;" rerender="showmsg"/>
  <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true" id="cancel"/>

</apex:pageBlock>
  </Apex:form>
</apex:page>

Please help me to solve this issue.
Hi, I got a question. If we upload data from a .csv file through data loader which has 500 rows and due to some error my data is uploaded till 100th row. Now I want to  upload my data from 101st row without again inserting from the starting. How could I do it?
I have a requirement where I have an external website outside Salesforce.The customer fills out a form on this website with name & other information. On submit of this form, I want a new custom object record to be created in salesforce with customer filled data on the form.Any help plz.