You need to sign in to do that
Don't have an account?
DeveloperSalesforce
Trigger on contact(before insert)
1. enter Name into XXX field (Lookup USer)
2.Then modify the code to update the owner of the contact to the Name
ownerId=Name
Any good idea to create trigger--Contact(before insert)??
2.Then modify the code to update the owner of the contact to the Name
ownerId=Name
Any good idea to create trigger--Contact(before insert)??
I am assuming that you need to update owner based on contact name.
Below are apex trigger and apex class for your trigger.
************************************************************************************************************************************************************************
Apex Trigger
------------------------------------------------------------------------------------------
trigger ContactTrigger on Contact(BEFORE INSERT, BEFORE UPDATE) {
// Before Insert
if (Trigger.isBefore && Trigger.isInsert) {
ContactTriggerHandler.manageContactOwnerBasedOnName(Trigger.New);
}
// Before Update
if (Trigger.isBefore && Trigger.isUpdate) {
List<Contact> listContacts = new List<Contact>();
for (Contact objContact:Trigger.New) {
if (objContact.Name != Trigger.OldMap.Get(objContact.Id).Name) {
listContacts.Add(objContact);
}
}
ContactTriggerHandler.manageContactOwnerBasedOnName(listContacts);
}
}
Apex Class
------------------------------------------------------------------------------------------
public with sharing class ContactTriggerHandler {
public static void manageContactOwnerBasedOnName(List<Contact> listContacts){
if (listContacts != null && listContacts.size() > 0) {
Set<String> setContactNames = new Set<String>();
for (Contact objContact:listContacts) {
setContactNames.Add(objContact.FirstName + ' ' + objContact.LastName);
}
List<User> listUsers = new List<User>([SELECT Id, Name FROM User WHERE Name IN:setContactNames]);
Map<String,User> mapNameUser = new Map<String,User>();
for (User objUser:listUsers) {
if (!mapNameUser.ContainsKey(objUser.Name)) {
mapNameUser.Put(ObjUser.Name,User);
}
}
for (Contact objContact:listContacts) {
if (mapNameUser != null && mapNameUser.size() > 0 && mapNameUser.Get(objContact.FirstName + ' ' + objContact.LastName) != null) {
objContact.OwnerId = mapNameUser.Get(objContact.FirstName + ' ' + objContact.LastName).Id;
}
}
}
}
}
************************************************************************************************************************************************************************
It will work like below,
- Contact Insert/Update with Name = "Test User1" (FirstName = "Test" and LastName = "User1")
- Will try to find user which have same name "Test User1"
- And update owner of contact with "Test User1"
Please let me know if you have other question/issue.
Thanks and Cheers,
Jigar