[SalesForce] Trigger to validate selection of Pick-list values

I got an object called 'Category' which has a master detail relationship with 'Scheme' object, 'category' has a pick list field called 'Type' & it has different values Ex:Cost,Time etc.

I need to write a trigger to validate selection of pick-list values. Once a pick-list value is selected it should not be used in another record and if user tries to select that same pick-list value and try to save in a new record, it should give an error and should not be able to save the record.

I'm bit confused as I have not done such scenario before.

Best Answer

Can you try the following code.It should work.

trigger Triggertovalidate on category__c (BEFORE INSERT,BEFORE UPDATE)
    {
        LIST<category__c> li = [select id,type from category__c where type != null]; 
        for(category__c c :trigger.new)
        {
         if(c.type != null){
          for(category__c existrecord :li)
          {
              if(existrecord.type == c.type){
              c.Type.adderror('Type is already used please select another one.');//If you need specify the SObject field also
              }
          }
         }
        }

    }
Related Topic