Create Validation Rules Through Code

 



#Salesforce #ValidationRules #ApexCode #CreateValidationRulesThroughCode


What is the Validation Rule in Salesforce? 

  • Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record.

  • A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of “True” or “False”

  • Validation rules also include an error message to display to the user when the rule returns a value of “True” due to an invalid value


Can we create a Validation Rule through code?
=> The answer is yes. We can create a validation rule through code. But, for this, you must have a MetaDataService Class in your org.

Here is a link, MetaDataSerivce Class.

The code is given below to create the Validation Rule:-

MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        List<MetadataService.Metadata> fields = new List<MetadataService.Metadata>();
        MetadataService.ValidationRule ValidationRule= new MetadataService.ValidationRule();
        ValidationRule.fullName='Account.Test'; // ObjectName.ValidationName
        ValidationRule.active=true;
        ValidationRule.errorConditionFormula= 'false';
        ValidationRule.errorMessage='Hello';
        fields.add(ValidationRule);
        MetadataService.SaveResult[] results = service.createMetadata(fields); 

Note:- In Validation.fullname, you'll provide Object API Name + . + Validation Rule Name.

Comments

  1. Replies
    1. Thanks for your valuable comment.

      Delete
    2. Hello Harsh,
      is it also possible to modify existing validation rules, e.g. deactivate them directly from APEX code? My last knowledge is no. Workaround: you have to insert a boolean validation rule bypass into the validation rule which you would control from the APEX code

      Delete
    3. It is not possible deactivate the existing validation rule with this code. But, yes you can do it with Metadata API. Please, don't worry about it, I'll make a blog on it.

      Delete
  2. I think the title of this blog post is a bit confusing. When I read it the first time I thought you would explain how to write Apex validation rule with addError() from SObject class.

    ReplyDelete
    Replies
    1. Thanks for your valuable feedback. I would keep it in my mind for a next time.

      Delete
    2. Hello Christian, I read the blog and this blog is to create validation rule of an object with code. So that you don't have to create manually.

      Delete

Post a Comment

Popular posts from this blog

Salesforce Certifications Exam and their Cost

How to create Salesforce Object with Code(MetadataService Class)