-1

I tried as below mentioned code, for adding field value in dynamic way

String type='Object__c';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
//getting required custom object
Schema.SObjectType patentSchema = schemaMap.get(type);
Map<String, Schema.SObjectField> fieldMap = patentSchema.getDescribe().fields.getMap();
Object__c obj = New Object__c();
for (String fieldName : fieldMap.keySet()) 
{ 
Schema.SObjectField schemafieldName = fieldMap.get(fieldName);
system.debug(schemafieldName);
//It provides to get the object fields label.
String fieldLabel = fieldMap.get(fieldName).getDescribe().getLabel();
//It provides to get the object fields data type.
Schema.DisplayType fielddataType = fieldMap.get(fieldName).getDescribe().getType();
if(fielddataType == Schema.DisplayType.Date)
{
    //system.debug('Field : '+fieldLabel+' | API Name : '+fieldName+' | DataType : '+fielddataType);
}
if(fieldLabel == 'Name')
{
    obj.fieldMap.get(fieldName).getDescribe() = 'Harsha';
}

}
system.debug(obj);

When I run this code in developer console I got the error

Error: Expression cannot be assigned

Thanks.

  • not absolutely clear for me, what are you trying to achieve ? – Oleksandr Berehovskyi Oct 25 '18 at 11:25
  • Do you want to dynamically add value to any record? – Pranay Jaiswal Oct 25 '18 at 11:29
2

obj.fieldMap.get(fieldName).getDescribe() = 'Harsha'; is your problem.

Your assignment statements must always have an "lvalue" - something that can receive an assigned value - on the left hand side. You have an expression here, a function call, although an invalid one since obj does not have a property fieldMap.

If what you're trying to do is dynamically assign to a field on your sObject obj, you can use put():

obj.put(fieldName, (Object)'Harsha');
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.