+ Start a Discussion
jgirard1.3931352457096028E12jgirard1.3931352457096028E12 

Trigger not firing before insert

Hey everyone, I'm new to the forum and to APEX in general, but was hoping someone could help me with the problem I'm having.

I have an object "Job" that has a lookup to another custom field "Well".  The Well object has a lookup back to Account standard object and the Job has a lookup to the Account object.  Job__r.Account__c is a required field.  Basically, I want our users to do the following: Click New to create a new Job record, choose the Well lookup, and the trigger needs to fire as soon as the Job__r.Well__c field is populated to populate the Job__r.Account__c field with that Well's related Account.id.  Hopefully that all makes sense!  Here is what I have so far, and the trigger is working, but I have to select an Account and save the record for the trigger to fire even when the trigger is a before insert.  If I choose an account that is not linked to the correct Well that I chose, it updates it perfectly, but I need it to automatically populate the Account field as soon as the Well is chosen.

trigger UpdateJobAccount on Job__c (before insert){
if (trigger.isBefore &&(trigger.isInsert||trigger.isUpdate))
{
  set<Id> WellIds = new set<ID>();
  for(Job__c job: trigger.new)
  {
    WellIds.add(job.Well__c);
  }
  Map<Id, Id> WellToAccountMap = new Map<Id, Id>();
  for(Well__c well :[select Id, Account__c from Well__c where id in: WellIds])
  {
       WellToAccountMap.put(well.Id,well.Account__c);
  }
  for(Job__c job: trigger.new)
  {
       job.Account__c = WellToAccountMap.get(job.Well__c);
  }
 
}
}
Kiru535Kiru535
Hi,

Please try this............

trigger UpdateJobAccount on Job__c (before insert){
if (trigger.isBefore &&(trigger.isInsert||trigger.isUpdate))
{
  set<Id> WellIds = new set<ID>();
  for(Job__c job: trigger.new)
  {
    WellIds.add(job.Well__c);
  }
  Map<Id, Id> WellToAccountMap = new Map<Id, Id>();
  for(Well__c well :[select Id, Account__c from Well__c where id in: WellIds])
  {
       WellToAccountMap.put(well.Id,well.Account__c);
  }
  for(Id wam: WellToAccountMap.keyset())

  {
       Job__c job = new Job__c();
       job.Account__c = WellToAccountMap.get(wam).AccountId;
  }

}
}

Regards,
Kirru
jgirard1.3931352457096028E12jgirard1.3931352457096028E12
Thanks for the quick response! I made the modifications to the trigger you asked, but am getting the error: “ Error: Compile Error: Initial term of field expression must be a concrete SObject: Id at line 17 column 56” It looks like it has something to do with the “job.FX5__Account__c = WellToAccountMap.get(wam).AccountId;” specifically the AccountId part. Regards, Justin [cid:image001.gif@01CF3144.AB5F2430] Justin Girard Sales Engineer 24 E Greenway Plaza, Suite 405 Houston, TX 77046 (832) 589-1467 (direct) (713) 552-9250 (office) (713) 552-9251 (fax) (409) 658-9994 (mobile)
jgirard1.3934427306193726E12jgirard1.3934427306193726E12
Any other ideas?