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
Jingyuan XieJingyuan Xie 

trigger to insert oppty account's ultimate parent account value before opportunity creation

Hello everyone , i am trying to write a trigger before oppty creation or update , populate account's ultimated parent account if it present, but not having any luck with my code, and i don't know how to fetch account's ultimated parent account based on account hirechy please help to review ,big thanks!

trigger populateultimateparentaccount on opportunity(Before Insert, Before Update) 
{
    Map <Id, Id> ultimateaccountMap = new Map <Id, Id> ();

    for (Opportunity account : trigger.new)
    {
        ultimateaccountMap.put(account.xxxxxxx, null);
    }

    for (Account account : [SELECT Id, xxxxxx FROM Account WHERE xxxxx IN :ultimateaccountMap.keySet()])
    {
        ultimateaccountMap.put(ultimateaccountMap.get(account.xxxxxx), account.Id);
    }

    List <opportunity> NewOppToUpdate = new List <opportunity> ();

    for (opportunity account : trigger.new)
    {
        if (ultimateaccountMap.containsKey(account.xxxx) 
        {
            // Existing account ultimate parent found
            Opportunity newopportunity = new Opportunity(Id = ultimateaccountMap.get(account.xxxx));
  

    update newopportunity;
}
SFDC EvangelistSFDC Evangelist
Hi Jingyuan,

Finding the "Ultimate Parent" need to evaluate how many levels of Parent each Account has. This level can not be consistant; and one Account can have 2 levels of parents where another Account can have 5 levels of Parent.

I think if you can change your deisgn little bit; it will be feasible solution. Add one more Lookup in Account, called "Ultimate Parent" and add the ultimate parent Account in this lookup. This fild will be BLANK; where some Account itself is ultimate Account and has only child.

This way you can get the Ultimate Parent from your SOQL.

Thanks!
Jingyuan XieJingyuan Xie
thanks Arindam for replying this ,actually , we'v had "Ultimate Parent"  lookup field in account object and also had workflow to populate account's ultimate parent into oppty
the reason why i need to write a before trigger is , the workflow only work after oppty record being created or oppty ID creation , however as we had one lookup fileter on oppty lookup field and the critiea is vertify if oppty's ultimate parent ID = look up field's ultimate parent ID ,therefore i must find a way to populate ulitmate parent lookup field on oppty create record creation . i'm new for writing an apex trigger , could you advise on the existing code based on my request ,thanks
lets say 
ultimate parent lookup field in oppty = UltimateAccount
ultimate parent lookup field in account=UltimateParent