[SalesForce] need help on Custom Metadata Type

I have one object Lead Support.In lead Support i have one Field QueueLabel__C.

And I created one Custom Metadata with Name Queue_metadata and in that i have one field Queue_Label_c

Requirement:when I am going to enter a record in Lead_Support Object it needs to check Quueulabel with same name is available in Metadata Object(Queues_Label__mdt) or not and if not then Error.

I am not able to make it bulkify.Please suggest

trigger CheckQueue on Lead_Routing__c (before insert,before update){
    list<String>Queulabel=new list<string>();
    for(Lead_Routing__c lc:trigger.new){
    Queulabel.add(lc.Queue_Name__c);
    }
    list<Queues_Label__mdt> listq=new list<Queues_Label__mdt>([select   Queue_Spec_Label__c FROM Queues_Label__mdt]);
    for(Lead_Routing__c lc:trigger.new){                  
          system.debug('lc>>>>'+lc);
        for(Queues_Label__mdt ss:listq){                  
               system.debug('ss>>>>'+ss);
           integer count=0; 
            System.debug('Inside next for count'+count);
            if(lc.Queue_Name__c!=ss.Queue_Spec_Label__c)   
            {
                 System.debug('Inside If list count'+count);
               count++;
                System.debug('count>>>'+count);
                if(count==1){
                     System.debug('Inseide If count'+count);

                    lc.adderror('Queue Label is Wrong');
                }

            }
        }
    }
}

Best Answer

This is one of those rare cases where salesforce allows a query inside a loop, because queries to custom metadata types are free, so you should take advantage of that behavior.

for(Lead_Routing__c record: Trigger.new) {
    if([SELECT COUNT() 
        FROM Queues_Label__mdt
        WHERE Queue_Spec_Label__c = :record.Queue_Name__c] == 0) {
        record.Queue_Name__c.addError("Value does not exist.");
    }
}

If you need to do something else with the metadata, you may want to query it into a variable instead, but since such queries are basically free, it probably doesn't matter for most trivial cases.

Related Topic