I am trying to get the default value of field but an error is coming.

List<String>apiNames =  new list<String>();
for(string apiName : des.fields.getMap().keySet()){
    taskFieldCreation.apiName = Task.apiName.getDescribe().getDefaultValue();

Error: Compile Error: Invalid field apiName for SObject Task


You want to use the field tokens, not the API Name, which is just a string. Also, you need to use SObject.put in order to set a dynamic field to a value, instead of the usual dot notation.

This should work:

Map<String, SObjectField> taskfields = des.fields.getMap();
for(String apiName: taskfields.keySet()) {
    SObjectField field = taskfields.get(apiName);
    taskFieldCreation.put(field, field.getDescribe().getDefaultValue());
  • thanks for the reply. SObject field = taskfields.get(apiName); error is coming on this line Error: Compile Error: Illegal assignment from Schema.SObjectField to SObject
    – Anzar
    Apr 3 '17 at 7:46
  • @Anzar, The error is descriptive enough, change declaration SObject field to SObjectField field. I think it is a typo.
    – Raul
    Apr 3 '17 at 8:28
  • 1
    @Anzar I apologize, it was indeed a typo. Changing it as I've just edited into the answer should fix the problem.
    – sfdcfox
    Apr 3 '17 at 8:39

Try this:

Map<String, Schema.SObjectField> mapFields = 
for(string apiName : mapFields.keySet()){
    // default value

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.