0

I have standard Picklist field currency on Lead object. I have a trigger, which checks when countrycode='86' then it will set the currency as 'CNY' otherwise set it to 'USD'.

Now my requirement is that when user try to manually change the picklist field value which dosn't match with countrycode then no update operation performed.

My code logic is:

 if(Trigger.isInsert || Trigger.isUpdate)
 {
       for (Lead lead :(List<Lead>)trigger.new)
               {
                  if(lead!=null &&  lead.Country_Code__c=='86')
                   {
                   Lead l=new Lead();
                   l.CurrencyIsoCode='CNY';

               }
                 else

                 {
                   Lead l=new Lead();
                   lead.CurrencyIsoCode='USD';
                 }    
           }
      }
 }
  • 1
    Why are you typecasting trigger.new to List<Lead>? FYI, trigger.new will hold the list of sObject records, in your case I assume it is Lead, therefore, you don't need to explicitly typecast it. – Mahmood Feb 10 '17 at 13:55
  • 1
    Second, which trigger event are you using? Before or After? Do you mind sharing entire trigger code? – Mahmood Feb 10 '17 at 13:57
  • @Mahmood if you use one of the trigger context collections (new, old, newmap, oldmap) outside of a trigger (i.e. in a separate apex class), then you have to cast the collection. At compile time, the type of Trigger.new is only List<MyObject> inside of a trigger on MyObject. Everywhere else, the type is List<sObject>. If you don't cast it, you'll get a compilation error saying that Loop variable must of of type sObject – Derek F Feb 10 '17 at 17:01
  • I totally agree Derek, but OP mentioned trigger in the question, not helper class or something similar. In case of trigger its not required. – Mahmood Feb 10 '17 at 17:28
0

A simple validation rule would be sufficient...

ISCHANGED(CurrencyIsoCode) && 
NOT(ISPICKVAL(CurrencyIsoCode, "CNY")) &&
Country_Code__c == "86"

This validation rule will check to see if the currency field is being changed to something other than "CNY" when the Country Code is 86 and allow you to error the update. You could also accomplish this in your trigger but a simple validation rule will be more maintainable in the future.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.