0

I am trying to achieve a list like this

(conWrapper:[BankName=abcd, Branch=main, phone=123456789],
 conWrapper:[BankName=abcd, Branch=main, phone=987654321])

From below class,

public without sharing class SendData{
    @AuraEnabled
    public static Object processData(string contId) { 
        if(String.isNotBlank(contId)){              
            List<Contact> con = [Select BankName__c, Branch__c, Phone1__c, Phone2__c from contact where id =: conid];
            
            List<reqWrapper> conWrapper = new List<reqWrapper>();
            for (Contact c : con){
                reqWrapper r = new reqWrapper();                
                if(String.isNotBlank(c.Phone1__c)){
                    r.BankName = c.BankName__c;
                    r.Branch = c.Branch__c;
                    r.phone = c.Phone1__c; //123456789
                    conWrapper.add(r);
                }
                if(String.isNotBlank(c.Phone2__c)){
                    r.BankName = c.BankName__c;
                    r.Branch = c.Branch__c;
                    r.phone = c.Phone2__c; //987654321
                    conWrapper.add(r);
                }
                                
            }            
        }
        return conWrapper;
    }

    public class reqWrapper{
        @AuraEnabled public string BankName;
        @AuraEnabled public string Branch;
        @AuraEnabled public string phone;
    }
}

but this is what I am getting

(conWrapper:[BankName=abcd, Branch=main, phone=123456789],(already output))

Can someone help me here, thanks in advance.

2

You're reusing the same "instance" of your object in memory. You can think of an instance like a box. You can only put one value in the box, and if you put in another one, you'll have to remove the old value first.

You need to create a new object for each row.

            if(String.isNotBlank(c.Phone1__c)){
                reqWrapper r = new reqWrapper();                
                r.BankName = c.BankName__c;
                r.Branch = c.Branch__c;
                r.phone = c.Phone1__c; //123456789
                conWrapper.add(r);
            }
            if(String.isNotBlank(c.Phone2__c)){
                reqWrapper r = new reqWrapper();                
                r.BankName = c.BankName__c;
                r.Branch = c.Branch__c;
                r.phone = c.Phone2__c; //987654321
                conWrapper.add(r);
            }
                            
1
  • how did I miss that, that worked! thank you so much @sfdxfox!!
    – user62694
    Feb 20 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.