I have created a trigger to create a new BO__c(BO__c is a custom object and having a lookup relation with Opportunity) record upon closing the opportunity(i.e Opportunity stage equal to Closed/Won), and it's working fine. Now I want to auto-populate custom Account__c lookup field in Opportunity on BO__c custom object, can any one help me here. Here is my code where I tried to get the Account__c field in Opportunity into BO__c object as BO_Account__c.

trigger Create_New_BO on Opportunity(after insert, after update)
    List<BO__c> lstintop = new List<BO__c>();

//Loop for each new and closed won opportunities
    for(Opportunity opty: Trigger.new)
     if((Trigger.oldMap == null ||'Closed Won' != Trigger.oldMap.get(opty.Id).StageName) && (opty.StageName == 'Closed Won') && (opty.OpportunityWon__c == False) )
        BO__c bo_opt = new BO__c();  

          bo_opt.opportunity__c = opty.id;
//        bo_opt.BO_Account__c = opty.Account.Name;(unable to get Account lookup field into newly creaed BO__c record here)
          bo_opt.Name = opty.Name;
          bo_opt.Commission__c = opty.Commission__c;
          bo_opt.Amount__c = opty.Amount;
          bo_opt.Category__c = opty.Category__c;

          bo_opt.Brands__c = opty.Brands__c;


insert lstbo_op;
                integer i = 10/0;

}catch(Exception ex){
system.debug('An exception occured in trigger named "Create_New__BO" and the exception is::'+ex);

  • What's the data type of BO_Account__c custom field? – RCS Jun 4 '18 at 12:24
  • It's also a lookup field. – Laxman Jun 4 '18 at 12:37

Edit the following line:

//        bo_opt.BO_Account__c = opty.Account.Name;(unable to get Account lookup field into newly creaed BO__c record here)


bo_opt.BO_Account__c = opty.AccountId;

AccountId should populate with the Account's Id.

  • Thank you!! @crmprogdev for the quick response, but unfortunately it's not working. – Laxman Jun 4 '18 at 12:15
  • When you say "its not working", what part of it isn't working? Try adding a system.debug at that line to check the value of opportunity.account to see why the lookup is not working. You could try opporutnity.account.Id, but that shouldn't be necessary. You shouldn't need to query for the Id. – crmprogdev Jun 4 '18 at 12:20
  • Here is debug log for the account assignment, looks like it's assigning null value. 17:53:15:035 VARIABLE_ASSIGNMENT [27]|this.BO_Account__c|null|0x33f7d20e – Laxman Jun 4 '18 at 12:29
  • I just looked it up and edited my answer. The correct field is what I'd originally answered with and then edited. LOL. Use the Opportunity.AccountId field. My apologies for leading you astray. That should resolve the issue. – crmprogdev Jun 4 '18 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.