You need to sign in to do that
Don't have an account?
Auto Populate "Account" Field Based On "Contact" Field Lookup
Hi all,
I'm having trouble autopopulating the account field when we select a contact based on lookup.
Currently, the user would have to lookup both the contact and the account fields. We would like
to just look up the contact field and it will autopopulate the Account lookup field with that contact
account. This would be used on the Orders section.
Would the following Apex Trigger work?
trigger IAR_trigger_Contact on Contact (before insert)
{
IAR_handler_Contact handler = new IAR_handler_Contact();
if(trigger.isInsert && trigger.isBefore && !IAR_handler_Contact.isCreatingAccountForContact)
{
handler.CreateAccountForContact(trigger.new);
}
}
Thank you!
public class IAR_handler_Contact {
public static Boolean isCreatingAccountForContact;
public IAR_handler_Contact() {
isCreatingAccountForContact = false;
}
public void CreateAccountForContact(List<Contact> newList)
{
isCreatingAccountForContact = true;
List<Contact> needAccounts = new List<Contact>();
for (Contact c : newList) {
if (String.isBlank(c.AccountId))
{
needAccounts.add(c);
}
}
if (needAccounts.size() > 0)
{
List<Account> newAccounts = new List<Account>();
Map<String,Contact> contactsByNameKeys = new Map<String,Contact>();
for (Contact c : needAccounts)
{
String accountName = c.Lastname + ' Household';
contactsByNameKeys.put(accountName,c);
Account a = new Account(name=accountName);
newAccounts.add(a);
}
insert newAccounts;
for (Account a : newAccounts)
{
if (contactsByNameKeys.containsKey(a.Name))
{
contactsByNameKeys.get(a.Name).AccountId = a.Id;
}
}
}
}
}
You Wrote trigger on the contact, are you trying to insert new accout whenever the contact is inserted?
Thanks,
pRAMODH.
I had some diffculty to understand the scenario for example If the user Picks the same contact for the different order are you creating the account again?
You cant use triggers to auto populate the fields on the page. Triggers are fired when a DML opeartion occurs like insert, update, delete
To Auto populate the fields use controller and VFpage.