+ Start a Discussion
dselatdselat 

Apex Trigger to remove value from multi-select field incase asset is deleted

Hello Gurus,

 

I've a requirement to remove a particular value from 'client product lines' (multi-select field) on Account object, if a related asset is deleted or a certain asset expiration criteria is met. How can I achieve this using apex trigger? I already have after insert, update trigger on Assets as follows:

 

 

trigger UpdateAccountCPLwSaaSAsset on Asset (after insert,after update) {
    //Get Triggered Opps
    List<Account> Accts = new List<Account>();
  for (Asset ass : Trigger.new) {
        if(ass.Contract_Type__c == 'SaaS'){
        for (Account acc:[Select Client_Product_Line_s__c from Account where Id=:ass.AccountId]){
            if (acc.Client_Product_Line_s__c==null){
            acc.Client_Product_Line_s__c='SaaS (Not Specific)';
            Accts.add(acc);}  
        else if(!acc.Client_Product_Line_s__c.contains('SaaS (Not Specific)')){
            acc.Client_Product_Line_s__c +=';SaaS (Not Specific)';
            Accts.add(acc);} 
            }
}
   }
if(!Accts.isEmpty()){
        update(Accts);
    }

}
Shashikant SharmaShashikant Sharma

This is your trigger

 

 

trigger UpdateAccountCPLwSaaSAsset on Asset (after delete) 
{
    //Get Triggered Opps
    List<Account> Accts = new List<Account>();
  for (Asset ass : Trigger.old) 
  {
        if(ass.Contract_Type__c != null)
        {
        for (Account acc:[Select Client_Product_Line_s__c from Account where Id=:ass.AccountId])
            {
            if (acc.Client_Product_Line_s__c != null && acc.Client_Product_Line_s__c.Contains(ass.Contract_Type__c){
            String newCPL;
            for(String s : String.valueOf(acc.Client_Product_Line_s__c).split(';'))
            {
                 if(s != ass.Contract_Type__c) 
                 {
                     if(newCPL == null)
                       newCPL = s;
                     else
                       newCPL = newCPL + ';' + s; 
                 }
            }
            acc.Client_Product_Line_s__c = newCPL;
            Accts.add(acc);}  
        
            }
          }
   }
if(!Accts.isEmpty()){
        update(Accts);
    }

}

 

 

 

I have not wrote this for bulk , please update it for it , you can see this for bulkifying http://forceschool.blogspot.com/2011/05/writing-apex-trigger-save-limits-in.html