Skip to main content
Premawati . (Deloitte USI) ha fatto una domanda in #Apex

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!!.

 
7 risposte
  1. 18 mar 2020, 18:54
    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 :)