Search code examples
salesforceapexsalesforce-lightning

How can I modify the meta data of any field using apex


I am trying to change the metadata of fields of a object in salesforce using Apex. For example I am trying to make all required field non-required. I was able to retrieve all the required fields using the schema class and using methods like isNillable(). I wanted to ask if there is any way I can modify the metadata.

I have searched a lot regarding this but could not find any helpful results.

Schema.DescribeSObjectResult a_desc = objects.get(Name_of_of_object_whose_fields_are_to_be_retrieved).getDescribe(); 

Map<String, Schema.SObjectField> a_fields = a_desc.fields.getMap();
Set<string> x=a_fields.keySet();


//I am making a map of fieldname and bool(field required or not)        
Map<String,boolean> result=new Map<String,boolean>();
for(String p:x)
result.put(p,a_fields.get(p).getDescribe().isCreateable() && !a_fields.get(p).getDescribe().isNillable() && !a_fields.get(p).getDescribe().isDefaultedOnCreate());
//what I want is to modify isNillable and other attributes and make these changes to the fields.

Solution

  • You can't make all required fields non-required because many of them are required at the database level and cannot be modified.

    For example, the Name field (on any object that has a Name field) is always required. You cannot change this property. Likewise, Master-Detail relationship fields are always required, on standard and child objects.

    To change the metadata of custom fields that are modifiable, you would have to use the Metadata API. It's not available in Apex, unless you use a wrapper like apex-mdapi. As a warning, modifying your org's metadata in a broad-based way via Apex is dangerous. You can cause damage to your org and its function in this way very easily. I strongly encourage you not to attempt to do this. Required fields are required for a reason.