You need to sign in to do that
Don't have an account?
Guide me through creating a trigger for updating a lookup field
Hi there,
I'm new to SF and have never used Apex, but it looks if this is where I have to end up. I'm trying to create my organization's implementation of SF and have reached a dead end. I would prefer to have a simple fix without spending many days learning Apex, so I would really super appreciate it if someone could share what this trigger's code should look like.
I am trying to automatically populate a lookup field on a custom object, InteractionParticipant__c. When a user enters a contact into the contact lookup field (Contact__c) on this object, I would like the account lookup field (Account__c) to be updated with the contact's associated account. It seems like I can't do this through workflow rules. Happy to take suggestions as to other ways to do this as well.
Thanks so much!
very basic first step
trigger populateAccount on OBJECTNAME (before insert, before update){
Map<ID,ID> conToAccount = New Map<ID,ID>();
Set<ID> conIDs = New Set<ID>();
for(OBJECTNAME o : trigger.new){
conIDs.add(o.Contact__c);
}
//Remove null just in case
conIDs.remove(null);
for(Contact c : [Select AccountID From Contact Where ID IN :conIDs])
conToAccount.put(c.id,c.AccountID);
for(OBJECTNAME o : trigger.new){
if(conToAccount.containsKey(o.Contact__c))
o.Account__c = conToAccount.get(o.Contact__c);
}
}
All Answers
very basic first step
trigger populateAccount on OBJECTNAME (before insert, before update){
Map<ID,ID> conToAccount = New Map<ID,ID>();
Set<ID> conIDs = New Set<ID>();
for(OBJECTNAME o : trigger.new){
conIDs.add(o.Contact__c);
}
//Remove null just in case
conIDs.remove(null);
for(Contact c : [Select AccountID From Contact Where ID IN :conIDs])
conToAccount.put(c.id,c.AccountID);
for(OBJECTNAME o : trigger.new){
if(conToAccount.containsKey(o.Contact__c))
o.Account__c = conToAccount.get(o.Contact__c);
}
}
Hi
try this
trigger triggername on InteractionParticipant__c(before insert) {
set<id> contactid = new set<id>();
public contact con;
for(InteractionParticipant__c IP:trigger.new) {
contactid.add(IP.contact__c);
}
con= [select id,accountId from contact where id=:contactid[0]];
for(InteractionParticipant__c IP:trigger.new){
IP.Account Id=con.accountid;
}
}
Thanks, though when I try to put this in, I get the error: Error: Compile Error: Invalid type: IP.Account at line 21 column 9. That line is where it says: IP.Account Id=con.accountid;
Ooh I think the first reply worked (last post referred to the second which I tried first)! I may have followup questions while I play around with it, but thanks so much!
Hi
try this
IP.Account__c = con.accountId