function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Can I have If statements in an update call?

I want to update the account object, but the value of the fields involved depends on the results of an IF statement. However, I don't seem to be able to put IF statements in the update record and I couldn't find any good examples to give me a clue.


Below is a sample of what I want to do conceptually, but can someone help with the correct syntax?


Thank you very much.


for(integer i=0; i <;i++){

ac.add(new Account(
ID =[i].AccountID, 

Date_Daily_Demo__c = if([i].Date_Daily_Demo__c > trigger.old[i].Account_Daily_Demo__c){[i].Date_Daily_Demo__c}; {trigger.old[i].Account_Daily_Demo__c})

update ac;


Best Answer chosen by Admin (Salesforce Developers) 

You want the "ternary operator".


All Answers




Below code is replica of your logic as per your description


List<account> lstacc = new lIst,account>();
for(integer i=0; i <;i++)
if([i].Date_Daily_Demo__c < trigger.old[i].Account_Daily_Demo__c)
 {[i].Date_Daily_Demo__c = trigger.old[i].Account_Daily_Demo__c;
} }

 Placed it in before triggers you dont even need update statement.



Sorry, I should have provided more info. This is an after update trigger on the Contact object that updates the related Account object. Since I'm not updating the Contact object, I believe I need the update call.


I will be evaluating 8 different date fields on the Contact object. These same 8 fields are on the Account object. I want to replace the Account field with the value in the Contact field, but only if the date on the Contact is greater than the date on the Account.


This is why, conceptually, I need to include if statetements in my Update Call. If value of the field on the Contact is greater than the related field on the Account, then update the Account field, otherwise do not.






Yes, if it is after update you need to have update call.


You can do this, but trigger can operate on bulk records so you need to take care or writing trigger generically.

You can write if statement as shown above before updating Account object as replica of contact object.



You want the "ternary operator".


This was selected as the best answer

Thanks. The ternary operator is new to me. I did some research and it looks like it would work.


I've already implemented a work-around solution using custom formula fields to handle the conditional logic and then I can always use the custom fileds in the update call.


Thank you for the response and introducing me to something new.