+ Start a Discussion
Avinash RaviAvinash Ravi 

Trigger to populate fields before insert before update

I'm trying to write a trigger that will populate fields such as region, country, etc from the user who creates the record, i.e, the owner.
This is what I've gotten so far
trigger UpdateValonServiceAgmt on Apttus__APTS_Agreement__c (before insert, before update) {

Map<String, User> UserMap = new Map<String, User> ();
 for(User temp : [Select Id, Name from User])
 UserMap.put(temp.Name,temp);

List<User> userList = new List<User> ();  

for(Apttus__APTS_Agreement__c agmt: Trigger.new)
    {
     if(trigger.isBefore && trigger.isInsert)
     agmt.Business_Contact__c = UserMap.get(agmt.Owner).Id ;

    }
}

But I keep getting an error that says "Error: Compile Error: Incompatible key type Name for Map<Id,User> at line 12 column 33". Right now I'm trying to populate a field called Business Contact from the user record. Likewise, I have to fill out the region and country from the user record as well.

Please help out.

Thanks in Advance.
Best Answer chosen by Avinash Ravi
Arunkumar RArunkumar R
Hi Avinash,

Hope you are trying to populate the record owner to the Business contact(User lookup) field. If yes, you can use the below code,
 
trigger UpdateValonServiceAgmt on Apttus__APTS_Agreement__c (before insert, before update) {

for(Apttus__APTS_Agreement__c agmt: Trigger.new)
    {
     // If you want this for update operation, then check update as well in the below if statement
     if(trigger.isBefore && trigger.isInsert)
     agmt.Business_Contact__c = agmt.ownerId;

    }
}

If this not works, let me know the exact issue.

All Answers

Arunkumar RArunkumar R
Hi Avinash,

Hope you are trying to populate the record owner to the Business contact(User lookup) field. If yes, you can use the below code,
 
trigger UpdateValonServiceAgmt on Apttus__APTS_Agreement__c (before insert, before update) {

for(Apttus__APTS_Agreement__c agmt: Trigger.new)
    {
     // If you want this for update operation, then check update as well in the below if statement
     if(trigger.isBefore && trigger.isInsert)
     agmt.Business_Contact__c = agmt.ownerId;

    }
}

If this not works, let me know the exact issue.
This was selected as the best answer
Ajay K DubediAjay K Dubedi
Hi,
You are populating the keyset of the map with the user name .The keyset should be unique so try to populate it with id of the user.
Also UserMap.get(key); will return the value for that key.Here its agmt.owner is not compatible with the keyset of the map you are using.
make the map with id vs user.

It will help you.

Thanks