function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RishuRishu 

Add record to custom object field with List results -Apex

I have a list of records (say mergelist), Now I want to add this list of records to a custom field (field2) which is on the same object.
Suraj Tripathi 47Suraj Tripathi 47
Hi Rishu,

You can take reference from this below code:-
List<account> accList=[select field1__c,field2__c from account LIMIT 100];
List<string> accField1= new List<string>();
for(account acc: accList){
    if(acc.field1__c!=null){
        accField1.add(acc.field1__c);
    }
}
for(string str: accField1){
    accList[0].field2__c=accList[0].field2__c+',  '+str;
}

if(accList.size()>0){
    update accList;
}
In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

 
RishuRishu
Hi Suraj,
Thanks for replying,
The requirement was to-
Import any field1(picklist) and field2(picklist) in field3 (new field of type multi picklist).

I have tried the below code, but it throws an error saying - variable does not exist: field3 
List<sObject> ppRecordsToupdate = new List<sObject>();
for(sObject ppRecord : [select id, name, from LLC_BI__Product_Package__c where
                                           (field 1 !=NULL OR field2 != NULL)])
{
    if(ppRecord.field1!=Null)
        ppRecord.field3 = ppRecord.field1;
    if(ppRecord.field2!=Null)
    {
        if(field3 !=NULL)
            ppRecord.field3 += ';' + ppRecord.field2;
        else
            ppRecord.field3 = ppRecord.field2;
    }
    if(field3 !=NULL)
        ppRecordsToupdate.add(ppRecord);
}
update ppRecordsToupdate;