1

Here in fld i have all fields of Lead Object and now i want to create a new Account and Name of the Account will be Lead's Name

public void show()
    {
        Schema.DescribeSObjectResult a_desc = Lead.sObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> a_fields = a_desc.fields.getMap();
        List<String> str = new List<String>();
        for(Schema.sObjectField fld:a_fields.values()){
            str.add(','+fld);
            //system.debug(fld);
        }
        String query = 'SELECT id'+str+' FROM Lead)';
        List<Lead> leadList = database.query(query);

        for(Lead sObjLead : leadList){
            Account acc = new Account();
            acc.name = sObjLead.name;
        }
    }
  • You do not have a Lead instance here - just information about the Lead object. Where is the data you want to use? – David Reed Jul 23 '19 at 15:31
  • I've made some changes in Code, can you please check now. Weather this is correct way or not.. – Dave Jul 23 '19 at 16:26
2
public void show()
    {
        Schema.DescribeSObjectResult a_desc = Lead.sObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> a_fields = a_desc.fields.getMap();
        String str = '';
        for(Schema.sObjectField fld : a_fields.values()){
            str += ','+fld.getDescribe().getName();
        }
        String query = 'SELECT '+str.removeStart(',')+' FROM Lead';
        system.debug('query => '+query);
        List<Lead> leadList = database.query(query);

        List<Account> accList = new List<Account>();
        for(Lead sObjLead : leadList){
            accList.add(new Account(Name=sObjLead.name));
        }
        system.debug(accList);
        // insert accList;
    }

This should work.

  1. fld is sObjectField, so you need to extract API name from its describe result.
  2. Change str to str (not list)
  3. Add new account to account like in loop
  • 1
    Thank You @salesforcesas for Explaining Point No.1 :) – Dave Jul 23 '19 at 16:57
1

Try this:

        Schema.DescribeSObjectResult a_desc = Lead.sObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> a_fields = a_desc.fields.getMap();
        List<String> strList = new List<String>();
        for(Schema.SObjectField field : a_fields.values()){
            strList.add(field.getDescribe().getName());
            //system.debug(fld);
        }
        String query = 'SELECT Id, ' + String.join(strList, ', ') + ' FROM Lead';

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.