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
Yogesh BiyaniYogesh Biyani 

Update an account field using Account trigger

I am still learning about triggers and for some reason following is not working. Any idea what is wrong? I do not get an error message, just that the trigger does not update the custom field. 
trigger populateRecName on Account (after insert,after update) {
    
    for(Account acc: trigger.new){
        if(acc.RecordType.Name == 'Joint Account'){
            acc.rec_type__c = 'Joint Account';
            update acc;
        }
    }
   
}
Olivia DavisOlivia Davis
I think you can use a before trigger instead of an after since you aren't referencing any system fields. You could also try adding a System.debug to see what is going.
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
trigger populateRecName on Account (before insert,before update) 
{

	Id accRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Joint Account').getRecordTypeId();
	
    for(Account acc: trigger.new)
	{
        if(acc.RecordTypeId == accRecordTypeId )
		{
            acc.rec_type__c = 'Joint Account';
        }
    }
   
}

Let us know if this will help you
 
Yogesh BiyaniYogesh Biyani
The updated code works, so, is acc.RecordType.Name == 'Joint Account'  not the right thing to do? 

 
Amit Chaudhary 8Amit Chaudhary 8
Hi Yogesh,

There was to manny issue in your code
1) You was doing the DML inside the for loop
2) You used After event.

Its always better to check recordTypeId. Let us know if this will help you