Finding if a custom field is editable using Apex code

I am reading the custom fields of a custom object Custom__c and then for each field I am inserting a new value:

  Public Custom__c custom1 {get;set;}

   Map<String, Schema.SObjectField> map = Schema.SObjectType.Custom1__c.fields.getMap();
   for(String fieldName : map.keySet()) {
    custom1.put(fieldName , 'some value');
   }

The problem is, some of the fields are made non-editable at when I do a put() on them, it gives me error.

What I want to do is

    Map<String, Schema.SObjectField> map = Schema.SObjectType.Custom1__c.fields.getMap();
   for(String fieldName : map.keySet()) {
       if(fieldName is editable) {
           custom1.put(fieldName , 'some value');
       }
   }

Is there a way in Apex to check if a custom field is editable? The custom fields are of different data types (text, reference, picklist..so on).

Making all fields editable in the admin side is not an option for me so I need a programmatic way to check for ‘editable’ condition.

Thanks for the help.

Answer

Map<String, Schema.SObjectField> fieldMap = Schema.SObjectType.Custom1__c.fields.getMap();
for(String fieldName : fieldMap.keySet()) {
    if(fieldMap.get(fieldName).getDescribe().isUpdateable()) {
        custom1.put(fieldName , 'some value');
    }
}

Attribution
Source : Link , Question Author : codeinprogress , Answer Author : Kasper

Leave a Comment