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
MSVRadMSVRad 

Trigger to populate lookup field not working

I am trying to pre-populate a custom lookup field on the Contact object with an account. This Account is the parent of the Account in the standard "Account Name" field on the Contact page. Facility is a child account, Practice is a parent account.

 

Here is what I have. It does not work - this is probably the 5th version of this trigger I have tried writing. I have logged a case with premier support - it has been escalated but I have not heard anything back.

 

Any Suggestions would be greatly appreciated.

trigger PopulatePracticeContact on Contact (before insert, before update) { //Set of Account Ids Set<Id> FacilityAccountIds = new Set<Id>(); for (Contact contactNew : Trigger.new) { //Facility Record Type == 012700000009R7G, always Child Account if(contactNew.Account.parentId != null && contactNew.Account.RecordTypeId == '012700000009R7G') { FacilityAccountIds.add(contactNew.AccountId); //A set of Facility Accounts } } Contact [] con = Trigger.new; con = [SELECT c.Id, c.Name, c.Related_Practice_Account__c, c.AccountId FROM Contact c WHERE c.AccountId IN :FacilityAccountIds]; Account [] pAccounts; pAccounts = [SELECT a.id, a.parentid, a.Name, (SELECT id, AccountId, Related_Practice_Account__c, Related_Practice__c FROM Contacts WHERE AccountId IN :FacilityAccountIds) FROM Account a WHERE a.id IN :FacilityAccountIds]; if(con.size()> 0){ if((con[0].AccountId == pAccounts[0].Id) && (pAccounts[0].ParentId != null)){ pAccounts[0].ParentId = con[0].Related_Practice_Account__c; } update con[0]; } }

 

Best Answer chosen by Admin (Salesforce Developers) 
MSVRadMSVRad

So here is the solution from sf premier support and it works.

 

trigger PopulatePracticeContact on Contact (before update, before insert) { //Set of Account Ids Set<Id> AccountIds = new Set<Id>(); for (Contact contactNew : Trigger.new) { AccountIds.add(contactNew.AccountId); //A set of Accounts } Map<Id, Account> pAccounts = new Map<Id, Account>([SELECT a.id, a.parentid, a.Name FROM Account a WHERE a.id IN :AccountIds]); for(Contact fcon : Trigger.New){ system.debug('Going to update Related Practice Account'); if(pAccounts != null && pAccounts.get(fcon.AccountId) != null) fcon.Related_Practice_Account__c = pAccounts.get(fcon.AccountId).ParentId; System.debug('Related Practice Account should be updated'); } }

 

Apparently I was totally over thinking this solution.  This will take the parent account that is related to the account that is related to the contact and populate the custom lookup field with the parentID.  Then the parent Account's contact related list will have the related contact displayed.
Message Edited by MSVRad on 08-21-2009 01:00 PM

All Answers

susheel1susheel1
Can u help me in writing a trigger tyo autopopulate a lookup field. I am new to Programming
MSVRadMSVRad

I obviously will not be of any help to you as my trigger I have written is not working for the purpose of autopopulating a lookup field.

 

I would suggest that you start out by looking at the cookbook and the developer guide. I dont think that anyone is going to just write a trigger for you so you might want to start looking at the documents provided by salesforce and post something for debugging help.

 

Here are the links:

 

Developer Guide

 

Cookbook You need to download the cookbook.

ahab1372ahab1372

would be helpful if you could post the error message.

 

My best guess is that you cannot reference any fields of the contact's Account without querying the Account first. This query must include the fields you want to reference later.

The Contact record in your trigger does not include any Account fields other than the AccountID.

 

What I think you need to do is:

  1. loop through the contacts in your trigger and write the accountIDs into a list
  2. (outside the loop) query the Accounts with the parent Account field and write them into a Map, using the AccountID as the key
  3.  loop through the Trigger contacts again and for each one, pull the parentAccountID from the map.

 

Pseudo Code (not sure if I got your custom fields right, not tested):

for(Contact contactNew:Trigger.New){ AccIDlist.add(contactNew.AccountID); } for(Account oneAccount:[SELECT ID, parentid from Account where ID IN :AccIDlist]){ AccountMap.put(oneAccount.ID, oneAccount); } for(Contact contactNew:Trigger.New){ contactNew.Related_Practice_Account__c = AccountMap.get(contactNew.AccountID).parentid; }

 

hope that helps,

Arnt

 

CaptainObviousCaptainObvious

You're looking to have a custom field populated as soon as you click the New Contact button? I don't think this can be accomplished by way of a trigger. The 'before insert' trigger actually fires after you click Save, so you will not see the field populated while editing the record.

 

Generally, when I need this kind of functionality, I create a VisualForce page and use a controller extension to query the necessary data. I can then pre-populate the fields in question using javascript.

 

For example...

 

 

<apex:page standardController="Pricing_Schedule__c" showHeader="true" sidebar="true" tabStyle="Contract" extensions="pricingScheduleExt"> <script type="text/javascript"> function populate() { var error = ''; error += document.getElementById("{!$Component.myForm.pgB.psError}").innerHTML if ( error=='' ) { document.getElementById("{!$Component.myForm.pgB.pgBSec.psQtyLwr}").value = '1'; document.getElementById("{!$Component.myForm.pgB.pgBSec.psQtyUpper}").value = '1000000'; document.getElementById("{!$Component.myForm.pgB.pgBSec.psContract}").value = '{!contract.contractnumber}'; document.getElementById("{!$Component.myForm.pgB.pgBSec.psIniDate}").value = '{!MONTH(contract.startDate)}/{!DAY(contract.startDate)}/{!YEAR(contract.startDate)}'; document.getElementById("{!$Component.myForm.pgB.pgBSec.psFinDate}").value = '{!MONTH(contract.endDate)}/{!DAY(contract.endDate)}/{!YEAR(contract.endDate)}'; document.getElementById("{!$Component.myForm.pgB.pgBSec.psTier}").value = '1'; } } window.onload=populate; </script> <!-- visualforce coding here --> </apex:page>

 

And the controller extension...

 

 

public class pricingScheduleExt { Contract contract; String cid; Pricing_Schedule__c pSchedule; public pricingScheduleExt(ApexPages.StandardController stdController) { pSchedule = (Pricing_Schedule__c)stdController.getRecord(); this.cid = ApexPages.currentPage().getParameters().get('cid'); } public Contract getContract() { contract = [SELECT ContractNumber, Account.Acronym__c, Product_group__c, Pricing_Model__c, StartDate, EndDate FROM Contract WHERE id = :cid]; return contract; } public PageReference customSave() { try { insert pSchedule; } catch ( DmlException exc) { ApexPages.addMessages(exc); return null; } return new PageReference('/' + pSchedule.Contract__c); }

}

 

MSVRadMSVRad

So here is the solution from sf premier support and it works.

 

trigger PopulatePracticeContact on Contact (before update, before insert) { //Set of Account Ids Set<Id> AccountIds = new Set<Id>(); for (Contact contactNew : Trigger.new) { AccountIds.add(contactNew.AccountId); //A set of Accounts } Map<Id, Account> pAccounts = new Map<Id, Account>([SELECT a.id, a.parentid, a.Name FROM Account a WHERE a.id IN :AccountIds]); for(Contact fcon : Trigger.New){ system.debug('Going to update Related Practice Account'); if(pAccounts != null && pAccounts.get(fcon.AccountId) != null) fcon.Related_Practice_Account__c = pAccounts.get(fcon.AccountId).ParentId; System.debug('Related Practice Account should be updated'); } }

 

Apparently I was totally over thinking this solution.  This will take the parent account that is related to the account that is related to the contact and populate the custom lookup field with the parentID.  Then the parent Account's contact related list will have the related contact displayed.
Message Edited by MSVRad on 08-21-2009 01:00 PM
This was selected as the best answer
ahab1372ahab1372

in my approach the query is actually NOT in the for loop, it is between 2 loops. It should be bulk proof.

 

The thing is that if you want to reference the parent account field, you have to query the account object at one point. Otherwise the information is not available in the trigger.

 

  • 1st iteration on the trigger records creates a list of account IDs
  • then (outside the above loop) you query the account object using the list of account IDs and store the results in a map
  • 2nd iteration on the trigger records updates the contact records with the values stored in the map

 

 

Message Edited by ahab1372 on 08-21-2009 12:21 PM
rsvrsv

Hi ,

 

Clicking on the related list button "New Contact"   in  Account  detail page  needs to prepopulate custom values from Acount To Contact. I have tried With Trigger The values are populating after saving . The requirement it must be populated Before saving i.e on Edit page  I came to Know Visual Pages will Solve this Problem  Please can you give Idea regarding how to implement  ?..

roysmith601.3493067652527424E1roysmith601.3493067652527424E1

Hi,
I have question about trigger.I create a custom object ="Product" on opportunity object .I create three (3) fields on custom object = Product and the filed description is below:
Field # 1:Application Received By(which is lookup(user)field)
field #2 : Closing Stage (pick list field; option is recieved)
field # 3: Closing Stage Owner ((which is lookup(user)field)

I have the requirment that :
If Application Received By not null
then
condition # 1 : set 
Closing Stage = recieved
and 

condition # 2 : set Closing Stage Owner = Application Received By

Example: If  
Application Received By = steve then according to workflow it should update the Closing Stage = recieved and Closing Stage Owner =steve

I create workflow for this and i am able to satisfy the condition # 1  but I am not to create work field update for condition # 2. 
I am new to salesforce and could anyone of you help me for writing this trigger.

thanks