Skip to main content

How to use MetadataService.cls to fetch metadata related Validation Rules of an Object

My requirement was to fetch few metadata in the Salesforce org like fields. Objet info, validation rule, workflow rule etc. Although Schema.describeSObjects can fetch you some of the metatda, you can’t fetch all types of metadata.

I found out that, we can make use of MetadataService class to fetch almost everything.


Sample Screenshots of the Application




How you use MetadataService class?

1.  Open this link - https://github.com/financialforcedev/apex-mdapi/tree/master/apex-mdapi/src/classes

2. Create classes named MetadataService.cls and MetadataServiceTesr.cls by copying the code from the above       link. Paste it in the target sandbox where you want to use it.

3. That’s all !!!  All you have to do is making use of the methods on the MetadataService.cls to get the                       metadata that you want.


Below is the sample code to fetch Validation Rules information.

	@AuraEnabled
    public static List<Validation> getvalidation(String currentobj)
{
List<String> sob=currentobj.split(',');
Validation v; //Wrapper objet to store Validation Rule info
List<Validation> vlist=new List<Validation>();

MetadataService.MetadataPort service = createService();
List<MetadataService.CustomObject> customObject =
(List<MetadataService.CustomObject>) service.readMetadata('CustomObject',
sob).getrecords();
System.debug(customObject);
for(MetadataService.CustomObject field : customObject) {
if(field.validationRules!=null)
{
for(MetadataService.ValidationRule fie : field.validationRules) {
System.debug(fie.fullName);
v=new Validation(fie.errorConditionFormula,fie.active,fie.fullName,field.fullName,fie.description);
vlist.add(v);
}
}
}

return vlist;
}
You can also follow this link to get some examples.
https://github.com/financialforcedev/apex-mdapi/tree/master/apex-mdapi/src/classes
If you need more info on this, tell us on comment setion.

Comments