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
prasanth sfdcprasanth sfdc 

error at custom object record insert from another object with dynamic fields.

Hi, 
      Here i have two objects have the same data type fields with api names. if i click on button then from one object record has to copy to another object.  so i am wrote this code in developer console for tesitng. i am getting this error. 

Line: 22, Column: 5
Invalid field t1 for SObject sai_prasanth__c   

Actually i want to get the field api name into temp string "t1"  but there my code thinking this "t1"  is custom field.  How to make string as api name here ?   
 
list<string> fields = new list<string>();
fields.add('name');
fields.add('comments__c');
fields.add('Cost__c');
fields.add('hotel_name__c');

string queryfields ='comments__c,Cost__c,hotel_name__c';
string tempname='lunch';
string query ='select id,'+queryfields+' from prashanth_kuamar__c where name=:tempname';

prashanth_kuamar__c pk =database.query(query);

system.debug(pk);

list<sai_prasanth__c> spToInsert = new list<sai_prasanth__c>();

for(integer i=0;i<fields.size();i++)
{
    system.debug('inside for loop: '+i);
    sai_prasanth__c sp= new sai_prasanth__c();
    string t1 = fields.get(i);
    sp.t1 = pk.t1;
    spToInsert.add(sp);
}
insert spToInsert;

 
Best Answer chosen by prasanth sfdc
Nayana KNayana K
Set<string> fields = new Set<string>();
fields.add('name');
fields.add('comments__c');
fields.add('Cost__c');
fields.add('hotel_name__c');

string queryfields ='name,comments__c,Cost__c,hotel_name__c';
string tempname='lunch';
string query ='select id,'+queryfields+' from prashanth_kuamar__c where name=:tempname';

list<sai_prasanth__c> spToInsert = new list<sai_prasanth__c>();

for(prashanth_kuamar__c objPK: Database.query(query))
{
    system.debug('inside for loop: '+objPK);
    sai_prasanth__c sp= new sai_prasanth__c();

    for(String strField: fields)
          sp.put(strField, objPK.get(strField));
    spToInsert.add(sp);
}
insert spToInsert;

 

All Answers

Nayana KNayana K
Set<string> fields = new Set<string>();
fields.add('name');
fields.add('comments__c');
fields.add('Cost__c');
fields.add('hotel_name__c');

string queryfields ='name,comments__c,Cost__c,hotel_name__c';
string tempname='lunch';
string query ='select id,'+queryfields+' from prashanth_kuamar__c where name=:tempname';

list<sai_prasanth__c> spToInsert = new list<sai_prasanth__c>();

for(prashanth_kuamar__c objPK: Database.query(query))
{
    system.debug('inside for loop: '+objPK);
    sai_prasanth__c sp= new sai_prasanth__c();

    for(String strField: fields)
          sp.put(strField, objPK.get(strField));
    spToInsert.add(sp);
}
insert spToInsert;

 
This was selected as the best answer
prasanth sfdcprasanth sfdc
Thank you very much.........