0

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()){
    apiNames.add(apiName);
    taskFieldCreation.apiName = Task.apiName.getDescribe().getDefaultValue();
 }

Error: Compile Error: Invalid field apiName for SObject Task

2

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);
    apiNames.add(apiName);
    taskFieldCreation.put(field, field.getDescribe().getDefaultValue());
}
3
  • 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
1

Try this:

Map<String, Schema.SObjectField> mapFields = 
    Schema.SObjectType.Task.fields.getMap();
for(string apiName : mapFields.keySet()){
    // default value
    System.debug(mapFields.get(apiName).getDescribe().getDefaultValue());
}

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.