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
Sainath VenkatSainath Venkat 

trigger to fetch the custom metadata to user

Hello Guys,

I am working on custom metadata, I have custom meta data "Org_Email_Signature__mdt" and is having field type Long text Area "Email_Signature__c".

Now, when I create a new user, I need to fetch that custom meta data to a field "Signature" in user object. I need to write a trigger for this.

Please help me to achieve this functionality.
Niraj Kr SinghNiraj Kr Singh
Hi sainath sai,

You may try this way, and let me know if it helps you!!
 
trigger UserUpdate on User (before insert) {
	List<Org_Email_Signature__mdt> lstMetaData = [SELECT Email_Signature__c FROM Org_Email_Signature__mdt];	
    if(trigger.isInsert && trigger.isBefore){
        for(User objNewUser : trigger.new) {
            objNewUser.Email = 'TestUser' + lstMetaData[0].Email_Signature__c; // COnsidering : lstMetaData[0].Email_Signature__c is having "@gmail.com"
        }
    }
}
Thanks
Niraj
 
Kt YadavKt Yadav
Hi sainath,

Please find below snippet.

trigger userSignature on User (before insert,after insert){
    
     if(trigger.isBefore && Trigger.isInsert){
        Org_Email_Signature__mdt[] signature = [SELECT MasterLabel,Email_Signature__c FROM Org_Email_Signature__mdt];
        if(signature!=nulll & !signature.isEmpty()){
            for(user usr : Trigger.new){
                usr.Signature = signature[0].Email_Signature__c;
            }
        }
    }
}
If you have any field on custom meta data that you want to compare before assigning the signaure , you can put it as a condition.

Please close this question if you find this solution correct or working.

Regards,
Keerti Yadav
 
Sainath VenkatSainath Venkat
Hi Keerti Yadav,

Can you help me with the test code for the trigger which you written if possible please.

Thanks
Sainath
Ajay K DubediAjay K Dubedi
Hi Sainath,

Below code can fulfill your requirements. Hope this will work for you.

trigger UserMetadataUpdate on User (before insert) {
    List<Org_Email_Signature__mdt> metadataList =  new List<Org_Email_Signature__mdt>();
    metadataList = [SELECT Email_Signature__c FROM Org_Email_Signature__mdt];
    
    if(metadataList.size()>0)
    {
    if(trigger.isInsert && trigger.isBefore){
        for(User objUser : trigger.new) {
            objUser.Email = metadataList[0].Email_Signature__c; 
        }
       }
    }
}

Please mark this as best answer if this solves your problem.

Thank you,
Ajay Dubedi