1

I am trying to set picklist value via Apex code. Please find the below details.

We have 2 picklist values in one field named Company Email with values 'Yes' & 'No'.

We want to set the values to picklist via Apex something like below

Account acc = [select id, Company_EmailOpt__c from Account where id = '0014E99999vIin'];   
acc.Company_EmailOpt__c = 'Yes'; 
update acc;

Now when we run this piece of code the picklist values has 2 'Yes' in the drop down. (attached screenshot)

enter image description here

It is quite confusing to the users.

Any suggestions?

  • 2
    Does your picklist have entries whose values do not match their labels? I suspect the value for the picklist entry whose label is 'Yes' is something other than 'Yes'. – David Reed Aug 28 '18 at 13:38
4

I think @david is right: The API name for the "Yes" picklist value may not be "Yes", so your apex code is adding what it thinks is a value that isn't in the set of picklist options. (You need to reference the API name from Apex in order to set it correctly, as of Spring '17. I'm not sure whether it's case-sensitive. That could be the problem.)

Here's a quick way to test this: Go to your picklist field and turn on "Restrict picklist to the values defined in the value set". Run your code again -- it should fail if we're right.

|improve this answer|||||
  • Yes you are correct. the API name was fifferent. But i again got into the same problem when i try with Translation. Consider a case if I use translation workbench so that Yes becomes Ja & No becomes Nej. Now it comes double as the API Name is 'Yes' & picklist value is 'Ja'. – Vishal Nayak Aug 30 '18 at 8:37
  • @VishalNayak -- That's odd. The SOQL query should return the API name for Company_EmailOpt__c, and the translation workbench should only change the display value; the API value remains the same. Is that what you're seeing? Even if the display value is Ja instead of Yes, as long as the API name is Yes, your setting the value to Yes in your code should work. – Shane Steinfeld Aug 30 '18 at 22:57
  • Vishal, were you able to get this working? – Shane Steinfeld Sep 30 '18 at 21:33

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.