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
Prema -Prema - 

URGENT Hi All, please help me with copying one object field values to another at one go !

I want to do something like this. How can it be possible , Please let me know :
for(Account acc2:[select id from account limit 1])
{
    //sObject s = new Account();
    Vehicle__c vt=new Vehicle__c();
    vt=(Sobject)acc2;
    insert vt;
    System.debug('sobject '+vt);
}

I don't want to do it like this :
for(Account acc2:[select id from account limit 1])
{
    
    Vehicle__c vt=new Vehicle__c();
    vt=acc2.name;
    insert vt;
    System.debug('sobject '+vt);
}

Here we are assigning the variables one by one. I have 157 fields how can I assign all of them in one go. Please help me this is bit urgent!!.

 
Best Answer chosen by Prema -
ayu sharma devayu sharma dev
Hello Prema 

I have an out of box solution for your problem but for this make sure that field type of all the map fields are same otherwise an error may occur.

The solution is to use the sObject.get() and sObject.put() methods. 
public static void premaMethod(){
    List<Vehicle__c> vehiclesToInsert = new List<Vehicle__c>();
    Set<String> AccountFields = getObjectFields( Account.SObjectType );
    Set<String> VehicleFields = getObjectFields( Vehicle__c.SObjectType );
    String accountFieldsString = String.join(new List<String>(AccountFields), ',');
    AccountFields.remove('id');
    for(Account acc2: Database.query( 'SELECT '+accountFieldsString+' FROM Account LIMIT1' ) ) {
        Vehicle__c vt = new Vehicle__c();
        for( String vField : VehicleFields ) {
            if( AccountFields.contains( vField ) ) {
                vt.put( vField, acc2.get( vField ) );
            }
            vehiclesToInsert.add( vt );
        }
    }
    if( vehiclesToInsert.size() > 0 ) {
        insert vehiclesToInsert;
    }
}

public static Set<String> getObjectFields( Schema.SObjectType sb ){
    Set<String> fields = new Set<String>();
    for(Schema.SObjectField fld: sb.getDescribe().fields.getMap().values()) {
        fields.add( fld.getDescribe().getName().toLowerCase() );
    }
    return fields;
}


Try to use this code. If you encounter any error let me know. If it solves your issue please mark this as best solution.

Thanks and Regards
Ayush Sharma :)

All Answers

sachinarorasfsachinarorasf
Hi Prema,

If you want to copy the records from Accounts to your custom object(Vehicle__c).
Then query all the fields of Account which fields you want to copy in the custom object but one thing must be remembered for copying is this the type of fields must be the same in both objects(Account and Vehical__c).
Then start the loop for Account and copy one by one field in custom object fields.
Then insert one by one or insert the list by adding records in the list.

For example-

for(Account acc2:[select id,Name,Industry from account limit 1])
{
    
    Vehicle__c vt = new Vehicle__c();
    vt.name = acc2.name;
    vt.Industry__c = acc2.Industry;
    insert vt;
    System.debug('sobject '+vt);
}

or 

List<Vehicle__c> vt = new List<Vehicle__c>();

for(Account acc2:[select id,Name,Industry from account limit 1])
{
    
    Vehicle__c vtInst = new Vehicle__c();
    vtInst.name = acc2.name;
    vtInst.Industry__c = acc2.Industry;
    vt.add(vtInst);
    System.debug('sobject '+vtInst);
}
insert vt;

I recommend the second example of using.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Sachin Arora
www.sachinsf.com
Prema -Prema -
Sachin, I've already informed that I don't want to go by this way..I was thinking if there's anything which we can do by one go without going for one by one assignment.. because I've thousands of fields.
ayu sharma devayu sharma dev
Hello Prema 

I have an out of box solution for your problem but for this make sure that field type of all the map fields are same otherwise an error may occur.

The solution is to use the sObject.get() and sObject.put() methods. 
public static void premaMethod(){
    List<Vehicle__c> vehiclesToInsert = new List<Vehicle__c>();
    Set<String> AccountFields = getObjectFields( Account.SObjectType );
    Set<String> VehicleFields = getObjectFields( Vehicle__c.SObjectType );
    String accountFieldsString = String.join(new List<String>(AccountFields), ',');
    AccountFields.remove('id');
    for(Account acc2: Database.query( 'SELECT '+accountFieldsString+' FROM Account LIMIT1' ) ) {
        Vehicle__c vt = new Vehicle__c();
        for( String vField : VehicleFields ) {
            if( AccountFields.contains( vField ) ) {
                vt.put( vField, acc2.get( vField ) );
            }
            vehiclesToInsert.add( vt );
        }
    }
    if( vehiclesToInsert.size() > 0 ) {
        insert vehiclesToInsert;
    }
}

public static Set<String> getObjectFields( Schema.SObjectType sb ){
    Set<String> fields = new Set<String>();
    for(Schema.SObjectField fld: sb.getDescribe().fields.getMap().values()) {
        fields.add( fld.getDescribe().getName().toLowerCase() );
    }
    return fields;
}


Try to use this code. If you encounter any error let me know. If it solves your issue please mark this as best solution.

Thanks and Regards
Ayush Sharma :)
This was selected as the best answer
Prema -Prema -
Thanks Ayush, This is the one which  I was looking for but I am running into an error when I execute this code (I have tweaked the code little bit)
public static void premaMethod(){
String str='\'';
    List<Vehicle__c> vehiclesToInsert = new List<Vehicle__c>();
    Set<String> AccountFields = getObjectFields( Account.SObjectType );
    Set<String> VehicleFields = getObjectFields( Vehicle__c.SObjectType );
    String accountFieldsString = String.join(new List<String>(AccountFields), ',');
    AccountFields.remove('id');
    Map<String, Schema.SObjectField> map2 = Schema.SObjectType.Account.fields.getMap();

    for(Account acc2: Database.query( 'SELECT '+accountFieldsString+' FROM Account where id='+str+'0016F00003cljWu'+str ) ) {
        Vehicle__c vt = new Vehicle__c();
        for( String vField : VehicleFields ) {
            if( AccountFields.contains( vField ) ) {
             if(map2.get(vField).getDescribe().isUpdateable())
             {
                System.debug('Fieldname '+map2.get(vField) +'  '+map2.get(vField).getDescribe().isUpdateable());
                vt.put( vField, acc2.get( vField ) );
             }
            }
            vehiclesToInsert.add( vt );
        }
    }
    if( vehiclesToInsert.size() > 0 ) {
        insert vehiclesToInsert;
    }
}

public static Set<String> getObjectFields( Schema.SObjectType sb ){
    Set<String> fields = new Set<String>();
    for(Schema.SObjectField fld: sb.getDescribe().fields.getMap().values()) {
        fields.add( fld.getDescribe().getName().toLowerCase() );
    }
    return fields;
}


Error : 07:53:56:191 EXCEPTION_THROWN [28]|System.ListException: Before Insert or Upsert list must not have two identically equal elements

 
Prema -Prema -
Oh I just checked, you have added the VehicleList at line number13, I pt that outside of the loop. So now it's not getting same values multiple times. I am able to save the record. Thanks for you help..
Prema -Prema -
public class ObjectReplication
{


public static void premaMethod(){
String str='\'';
    List<Vehicle__c> vehiclesToInsert = new List<Vehicle__c>();
    Set<String> AccountFields = getObjectFields( Account.SObjectType );
    Set<String> VehicleFields = getObjectFields( Vehicle__c.SObjectType );
    String accountFieldsString = String.join(new List<String>(AccountFields), ',');
    AccountFields.remove('id');
    Map<String, Schema.SObjectField> map2 = Schema.SObjectType.Account.fields.getMap();

    for(Account acc2: Database.query( 'SELECT '+accountFieldsString+' FROM Account where id='+str+'0016F00003cljWu'+str ) ) {
        Vehicle__c vt = new Vehicle__c();
        for( String vField : VehicleFields ) {
            if( AccountFields.contains( vField ) ) {
             if(map2.get(vField).getDescribe().isUpdateable()==true)
             {
                System.debug('Fieldname '+map2.get(vField) +'  '+map2.get(vField).getDescribe().isUpdateable());
                vt.put( vField, acc2.get( vField ) );
             }
            }
        }
         vehiclesToInsert.add( vt );
            System.debug('vehclList '+vehiclesToInsert);

    }
    if( vehiclesToInsert.size() > 0 ) {
        Database.saveresult[] results=Database.insert( vehiclesToInsert,false);
        for(Database.saveResult r: results){
            if(!r.isSuccess()){
                for(Database.Error err : r.getErrors()){
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('affected this error: ' + err.getFields());
             }
           
            }
            else if(r.isSuccess())
            {
                System.debug('Id '+r.Id);
            }
        }
        
        
    }
}

public static Set<String> getObjectFields( Schema.SObjectType sb ){
    Set<String> fields = new Set<String>();
    for(Schema.SObjectField fld: sb.getDescribe().fields.getMap().values()) {
        fields.add( fld.getDescribe().getName().toLowerCase() );
    }
    return fields;
}
}

 
ayu sharma devayu sharma dev
Glad that worked for you!