+ Start a Discussion
SambitNayakSambitNayak 

Trigger on Contact to populate a field based on a condition

Hi,
I need a before Trigger on Contact that will update my Job grade field based on what value I enter for Job Code.
For e.g: If I create a contact with name : John Smith and Job Code =101, the trigger will search the Job Code Object with Job Code =101 and return the corresponding Job Grade for that --- And populate my Job Grade field on the Contact object.
Thanks.
SambitNayakSambitNayak
        public static void beforeUpdate(List<Contact> contList){

        for (Contact con:contList){
            //When NULL Job Code is entered
            if(con.Job_Code__c==NULL){
                con.Salary_Job_Grade__c=NULL;
                //contsToUpdate.add(con);
            }
            //When Job Code is not NULL
            else{
                Job_Code__c jc =[SELECT Salary_Job_Grade__c FROM Job_Code__c
                                    WHERE Name =: con.Job_Code__c];
                //system.debug(jc);
                con.Salary_Job_Grade__c = jc.Salary_Job_Grade__c;
                //contsToUpdate.add(con);
            }           
        }


I tried this code but I am getting the 18 digit ID on the field rather that the actual value.
CharuDuttCharuDutt
Hii Sambit
Try Below Code
trigger testtrigger on Contact (before update) {
    string jobCode;
	for(contact con: trigger.new){
    jobcode = con.Job_Code__c;    
	}
    
    list<Job_Code_Object__c>lstJobCode = [select id,Name,Job_Code__c,Job_grade__c from 
                                          job_Code_Object__c where job_Code__c = :jobcode limit 1];
    for(contact con: trigger.new){
        if(!lstJobCode.isEmpty()){
        con.Job_Code__c = lstJobCode[0].Job_grade__c;
        }else{
            con.AddError('Job Code Not Found');
        }
	}
}
Please Mark It As Best Answer If It Helps
ThankYou!
SambitNayakSambitNayak
Thanks CharuDutt... That was really quick. Appreciate your help. Let me do some analysis.
SambitNayakSambitNayak
@CharuDutt: 1 more question.
I want to display an error if the job code entered is incorrect.
i.e: My code should be like:

if(Not Exists job_code__c){
con.addError('Please enter a correct Job Code')
}
CharuDuttCharuDutt
Hii Sambit 
i've Already Added The The Error Condition In My Code Above
trigger testtrigger on Contact (before update) {
    string jobCode;
	for(contact con: trigger.new){
    jobcode = con.Job_Code__c;    
	}
    
    list<Job_Code_Object__c>lstJobCode = [select id,Name,Job_Code__c,Job_grade__c from 
                                          job_Code_Object__c where job_Code__c = :jobcode limit 1];
    for(contact con: trigger.new){
        if(!lstJobCode.isEmpty()){
        con.Job_Code__c = lstJobCode[0].Job_grade__c;
        }else{
            con.AddError('Job Code Not Found');
        }
	}
}
Please Close Your Query By Marking It As Best Answer If It Helps. So it Also Helps Others In Future
ThankYou!