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
Saurabh Kumar 284Saurabh Kumar 284 

Write an apex trigger on Contact to populate "NA" in first name if Contact is created without First name.

Hi, I am at learning stage of Apex Trigger. So, can someone please help me with this question?
Best Answer chosen by Saurabh Kumar 284
Andrew GAndrew G
an example.
trigger ExampleTrigger on Contact (before insert, before update) {
    for(Contact c : Trigger.new) {
        if(String.isBlank(c.Firstname) {
            c.FirstName = 'NA';
        }
    } 
}
Explanation:

why before insert / before update?   We are updating the record that invokes the trigger.  Much better to do in before triggers.  Will also save on doing a DML as the field is updated before the record is written the first time.

why is there a FOR loop?   This bulkifies the trigger.  If there is a bulk update, this will handle it.

why String.isBlank ver c.FirstName == '' or c.FirstName == null or c.Firstname.trim() == '' or c.FirstName.size()==0   ?
isBlank(inputString)
Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.
ref: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm
therefore the String.isblank covers all the possibilities in the simplest code.



regards
Andrew
 

All Answers

Andrew GAndrew G
an example.
trigger ExampleTrigger on Contact (before insert, before update) {
    for(Contact c : Trigger.new) {
        if(String.isBlank(c.Firstname) {
            c.FirstName = 'NA';
        }
    } 
}
Explanation:

why before insert / before update?   We are updating the record that invokes the trigger.  Much better to do in before triggers.  Will also save on doing a DML as the field is updated before the record is written the first time.

why is there a FOR loop?   This bulkifies the trigger.  If there is a bulk update, this will handle it.

why String.isBlank ver c.FirstName == '' or c.FirstName == null or c.Firstname.trim() == '' or c.FirstName.size()==0   ?
isBlank(inputString)
Returns true if the specified String is white space, empty (''), or null; otherwise, returns false.
ref: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm
therefore the String.isblank covers all the possibilities in the simplest code.



regards
Andrew
 
This was selected as the best answer
Saurabh Kumar 284Saurabh Kumar 284
Thanks for your help, Andrew.