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
Sam AroraSam Arora 

create a trigger on Account

Hi,
Need to create a trigger on Account.which took first 1st alphabet of name 2nd alphabet of lastname(Sam Arora 'SA')and after that createddate field value  month and year .All the value insert in test__c field.Example(SA-122018)
Thanks in Advance!  
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Sam

Please find below the code for reference:

TRIGGER_ON_ACCOUNT_BEFORE_INSERT {

for(Account accountRecord : triggerNew) {
if(accountRecord.Name != null && accountRecord.LastName != null && accountRecord.Name.Length() >=1 &&  accountRecord.LastName.Length() >=2 )
accountRecord.test__c = accountRecord.Name.substring(0, 1) + accountRecord.LastName.substring(1, 2) + '-' + accountRecord.CreatedDate;
}
}

triggerNew contains value in test field.

Cheers!!!
Ajay K DubediAjay K Dubedi
Hi Sam,

Check the below code:

trigger UpdateFieldOnAccount on Account (Before insert) {
    
    if(trigger.isBefore && trigger.isInsert){
        
        for(Account a:Trigger.new){
            String tempVar='';
            if(a.Name != null){
               
                if(a.LastName!=null && a.LastName!= ''){
               tempVar=tempVar+a.Name.subString(0,1)+a.LastName.subString(0,1);
                }
                else{
                     tempVar=tempVar+a.Name.subString(0,1);
                }
 
                tempVar=tempVar+'-'+Date.today().month()+Date.today().year();
                a.test__c=tempVar;
            }
                       
        }
        
    }

}

But, we take createdDate as a current Date because we don't get createdDate before the insertion of an account record. 

Please mark it as Best answer if it helps you.

Thanks.
Ajay Dubedi