function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Suresh RaghuramSuresh Raghuram 

validation on a lookup field record type name

On Contact Object there is a look up for the Account I had to validate on record type of the Account object .

 

I wrote the code as follows but it is giving compiler errror saying variable not exist

 

If(Accounts__r.RecordType.Name != 'Business')

 

Error Msg.

Best Answer chosen by Admin (Salesforce Developers) 
Suresh RaghuramSuresh Raghuram

I did as below  and it is working thanks for your help

if(contact.AccountId != null){
       
            accRecordTypeId = [SELECT Id, Name, RecordTypeId FROM Account WHERE Id = :contact.AccountId].RecordTypeId;
            rt = new RecordType();
            rt = [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Account' AND Name = 'Consumer'];
      
        if(accRecordTypeId == rt.Id){
            isValid = false;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'CAN NOT SELECT CONSUMER'));
         }
         } 

All Answers

cmlcml

I believe you must be doing validation in your trigger code. Fields using lookups doesn't come in Trigger automatically. You need to query them first and then user it.

I hope this helps.

Suresh RaghuramSuresh Raghuram

I am trying this in a visual force page 

cmlcml

Even in visualforce page, you have to first query that and then use it. Something like this.

 

Contact con=[select Id,Accounts__r.RecordType.Name from Contact where id =: <Id> ][0];

 

and then use it in if statement :

 

if(con.Accounts__r.RecordType.Name =='Business')

{

 your code here

}

Suresh RaghuramSuresh Raghuram

I did as below  and it is working thanks for your help

if(contact.AccountId != null){
       
            accRecordTypeId = [SELECT Id, Name, RecordTypeId FROM Account WHERE Id = :contact.AccountId].RecordTypeId;
            rt = new RecordType();
            rt = [SELECT Id, Name FROM RecordType WHERE SObjectType = 'Account' AND Name = 'Consumer'];
      
        if(accRecordTypeId == rt.Id){
            isValid = false;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'CAN NOT SELECT CONSUMER'));
         }
         } 

This was selected as the best answer