Apex Tip: How to make a DML operation in a trigger After insert/update

Many times I’ve faced requirements to write a field in a trigger after the record is inserted or update. So, naturally I’ve tried something like this:

But there the record is read only and if you try to change a field value this exception will be fired:

execution of AfterInsert caused by: System.FinalException: Record is read-only

The workaround is quite simple. The object contained by the global trigger.new is read-only, but you can create a new object referring the same ID and change the value that you need.

In addition you have to avoid the recursion since you are changing the record the trigger will be fired again. To avoid that you have to use a static flag which says that the trigger has been already executed during the current executing context.

So, the final code should be like this:

Enjoy :)

Tip: the simplest way to list all objects

Since SFDC contains variable objects (custom and standard) we have many times to list them.

This is a simple snippet to do it.

Tip Apex: get SObject Type from Id

This is a really piece of cake apex snippet. Extremely useful when you are developing generic methods.

Tip Apex: Select * from X on apex (SOQL)

I’ve faced many times two problems on SOQL queries:

1. They have not * (star) operator and hence it is really tough to list all fields on large objects.
2. If you try to modify a field name or delete or update the type, salesforce won’t allow you if it is referenced on the code. It is really painful on deploys.

As a best practices when I have to retrieve all fields I use this simple function.

Apex Tip: check if field exists on SObject

This small function check if any SObject contains a field, really useful on many cases.

For instance if you want to know if country Picklist is active, you could check countryCode field active.

Other approach using JSON serializer

Sample use: