I am struggling to come up with a trigger to update an Account field (Last Survey Sent) when the same field gets inserted or updated on the Case (Last Survey Sent). I am unable to do this via workflow. Any help?
Survey gets sent -> Last Survey Sent field on Case is updated to TODAY() -> Last Survey Sent field on its Account gets set to the same date as the Last Survey Sent field on the Case.
Thanks,
Brian
Best Answer
You could use the following trigger code to keep the two in sync. Rename the Last Survey Sent to match your API name.
And the test class. This assumes that the Last Survey Sent field is writable on the Case object.
While it may seem more intuitive to query for the account, the use of
new
and then setting the ID protects you during bulk updates. If you had 1000 cases to update at once, it would require 1000 SOQL queries. Also note that I am adding the accounts to a list and updating the entire list after the trigger runs itsfor
loop. That's another technique for 'bulkifying' and protects against exceeding DML limits.Let me know if you have any other questions. I would be happy to walk you through writing unit tests for this trigger.