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
GhanesanGhanesan 

Restrict Parent Account to create an opportunity - Getting Error on Trigger

Getting Error on Trigger - Unexpected Token 'Account.Parent.Id'

Here is my Code:

trigger RestrictParentAccount on Opportunity (before insert){

list<Opportunity> Opp =  new List<Opportunity>();
    For(Opportunity Opp:trigger.New){
    List<Opportunity> OptyAcc = [Select id From Opportunity WHERE AccountId = Account.Parent.Id];
    {
      If(OptyAcc.size() > 0){
         opp.AddError('Opportunity Cant be created by Parent Account');
    }
  }
}
}

 
Best Answer chosen by Ghanesan
AnkaiahAnkaiah (Salesforce Developers) 
Hi Ghanesan,

try with below code.
trigger parentaccount on Opportunity (before insert) {
    
    set<id> parentids = new set<id>();
    
    for(opportunity opp :trigger.new){
        
        if(opp.accountid != Null){
            parentids.add(opp.AccountId);
        }
    }
    
    Map<id,Account> mapaccs = new map<id,account>();
    for(account acc:[select id,parentid,parent.parentId from account where parentId=:parentids OR parent.parentId=:parentids]){
     mapaccs.put(acc.id,acc);  
    }
    for(opportunity opp :trigger.new){
        If(mapaccs.size()>0) {
         opp.adderror('Opportunity Cant be created by Parent Account');   
        }
    }  
}

If this helps, Please mark it as best answer.

Thanks!!

All Answers

AnkaiahAnkaiah (Salesforce Developers) 
Hi Ghanesan,

try with below code.
trigger parentaccount on Opportunity (before insert) {
    
    set<id> parentids = new set<id>();
    
    for(opportunity opp :trigger.new){
        
        if(opp.accountid != Null){
            parentids.add(opp.AccountId);
        }
    }
    
    Map<id,Account> mapaccs = new map<id,account>();
    for(account acc:[select id,parentid,parent.parentId from account where parentId=:parentids OR parent.parentId=:parentids]){
     mapaccs.put(acc.id,acc);  
    }
    for(opportunity opp :trigger.new){
        If(mapaccs.size()>0) {
         opp.adderror('Opportunity Cant be created by Parent Account');   
        }
    }  
}

If this helps, Please mark it as best answer.

Thanks!!
This was selected as the best answer
GhanesanGhanesan
Thanks Ankaiah, You are the best. And i was tried this scenario in LookupFilter on Opportunity Object. But it doesnt work. Can you tell me is it possible on LookupFilter? if so, I have shared the SS please spot the mistake i have done. 
Field:  Account Name: Account Name
 Operator: Equals
Value/Field: Field - Account Name: Parent Account: Account Name

User-added image