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
MigMig 

Cross Object ( Account-Contact ) Apex trigger problem when insert ! update is ok !!

The trigger will bring to each contact the website of the related account ;

This code works when I update a Contact. But it did not work when I create it. Can someone please help me:

Code:
trigger ContactTriggertest on Contact (before update, before insert) {
 Contact[] ILtoUpdate = new Contact[0];
 Boolean doUpdate = false ; 
 Id [] searchID = new Id [1];
 for (Contact ils : Trigger.new) {
  searchID[0] = ils.Id ; 
  for (Contact  a : [Select c.id, c.Account.Website From Contact c WHERE id in : searchId]) {
   if ( a.id != null){
    ils.Account_Web_Site__c = a.Account.Website;
    if (ils.Account_Web_Site__c != a.Account.Website){
         doUpdate = true ;
    }
        if (doUpdate){
          ILtoUpdate.add( ils );
         }
   }
  }
 }
 if (!ILtoUpdate.isEmpty()) {
      update ILtoUpdate;
 }
}

 When I create a contact, it does not work. and if I update it it will fill in the good website. Why ?


This is reallly really really an important functionnality I need to my organisation.
( for info This is juste an exemple because I will use the same code structure in other SObjects with a lot of fields )

Thank you in advance for your help !!!!!!!!!!!!!



Message Edited by Mig on 04-04-2008 05:41 PM

Message Edited by Mig on 04-04-2008 05:42 PM

Message Edited by Mig on 04-04-2008 05:56 PM
A_SmithA_Smith
The contact isn't assigned an Id until after it is inserted.  Your trigger is trying to query the contact object before the record exists:
 searchID[0] = ils.Id ; 
for (Contact a : [Select c.id, c.Account.Website From Contact c WHERE id in : searchId])
I would suggest creating an array of all the account Ids you'll need and then running a query on the account object directly to get the web site.  Then loop through all the contacts in the trigger and lookup the web site for each (use a Map to store the result set of the account query as it will make getting the web site easier as you loop through the contacts).

Andrew
MigMig
Thank you very much. I took my time to understand your explanations and about 10 minutes reading your answer I finally Understood ^_^ and my trigger works fine now.

It's nice to have some pple who take the time to answer. Tk you one more time.

Mig