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
sfadm sfadmsfadm sfadm 

After Update Trigger not updating a record field

I'm using the after update trigger to update the "BillingCity" field in the Account object and make the field in proper case.
 
trigger on Account (after update) {

            String billingCity = Account.billingCity;

            toTitleCase(billingCity);
}

And the code in the invoked toTitleCase(billingCity) method:
 
//converts a given string to Title Case where the
//first letter of every word is capitalised and the rest are small
public String toTitleCase(String billingCity) {
   System.debug('billingCity ' + billingCity);
   String titlePhrase = '';
   //a set of words that should always be in lower case when in Title Case
   Set<String> forceLower = new Set<String>{'of', 'the', 'for', 'and', 'a', 'to', 'at' ,'an', 'but', 'if', 'or', 'nor'};

   if(billingCity != null && billingCity.length() > 0){
      String[] splitPhrase = billingCity.trim().split(' ');

      for(integer i = 0; i < splitPhrase.size(); i++){
          if(!forceLower.contains(splitPhrase[i].toLowerCase()) || i == 0 || i == (splitPhrase.size()-1) ) {
             titlePhrase += (splitPhrase[i].substring(0,1).toUpperCase())+(splitPhrase[i].substring(1).toLowerCase())+' ';

          } else {
               titlePhrase += splitPhrase[i].toLowerCase()+' ';

               }
          }
       }

       return titlePhrase.trim();
}
In the debug log I can see that the "BillinCity" field is updated with the proper case:
 
17:00:57:945 USER_DEBUG [40]|DEBUG|billingCity San Marino
but on a record level the field remains with upper case: "SAN MARINO"

Please advise an appropriate solution.

 
Best Answer chosen by sfadm sfadm
David @ ConfigeroDavid @ Configero
trigger MyAccountTrigger on Account (before insert, before update) {
    for (Account account : Trigger.new) {
        If (String.isNotBlank(account.BillingCity)
            && (Trigger.isInsert || Trigger.oldMap.get(account.Id).BillingCity != account.BillingCity)) {
            account.BillingCity = toTitleCase(account.BillingCity);
        }
    }
}


Three major problems with your current trigger
  • It is calling toTitleCase(), but not using the return value of that method and saving it to the Account's BillingCity field.
  • You are running in an after trigger which requires you to call another DML statement to update any records, in contrast to a before trigger which can manipulate field values for the trigger without any DML statement.
  • You are not handling inserts, which should have the data cleansed just as much as an update (only when the Billing City is changed though)

Please mark this answer as correct if it helped you!