[SalesForce] Compare two fields

I have 2 object A,B

A has 2 field id, name

B has 3 field id, name, ismatching(default 0)

Scenario is >> if I insert value in B , it should be compare B.name to A.name , if match is true then ismatching field update from 0 to 1,

I am using trigger for that but facing problem will you please suggest me .

here A is Whitelist__c and B is CrawleLink__c. and trigger is

trigger white_list_update on CrawleLink__c (before insert) 
{ 
    List <Whitelist__c> nam = [select name from Whitelist__c]; 
        for(CrawleLink__c cc : Trigger.new) { 
            for(Integer i= 0; i<nam.size(); i++) { 
                String aa= nam[i]; 
                if(aa==cc.Domain__c) { 
                cc.Whitelist__c = 1; 
            } 
        }    
    } 
}

Best Answer

Try this one.

trigger white_list_update on CrawleLink__c (before insert) 
{ 
    List <Whitelist__c> nam = [select name from Whitelist__c]; 

    Set<String> whiteListNames=new Set<String>();
    for(Whitelist__c w: nam){
        whiteListNames.add(w.name);
    } 
    for(CrawleLink__c cc : Trigger.new) { 
        if(whiteListNames.contains(cc.Domain__c)){
            cc.Whitelist__c = 1; 
        } 
    } 
}

Here i'm using SET to store names and checking if SET contain the name, set flag variable to 1.

Note: This logic should be on before update too because if name changes to a matching one the flag need to be updated.

For best practices use a separate class say White_list_updateHelper and create separate methods and call them from trigger.