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
Anik soni 7Anik soni 7 

I am stuck on this..!!

When an account is inserted or updated,check whether any opportunity is linked to it or not,if not then create one whose name is ‘First Opportunity -<Account Name>’.
Here is my code:


trigger CheckOpportunitys on Account (before insert, before update) 
{
    if(trigger.isafter)
    {
        if(trigger.isinsert)
        {
            for(account acc : trigger.new)
            {
                List<opportunity> op = [Select Name from opportunity where accountid = :acc.Id];
                if(op.isempty())
                {
                    Opportunity opp = new opportunity(Name = 'First opportunity'+ acc.Name, Stagename ='Qualification',CloseDate = date.today(), accountid = acc.Id);
                    op.add(opp); 
                } 
                Else
                {
                    System.debug('This opportunity is already EXIST'); 
                }
                insert op;
            }
        }
    }
    else if(trigger.isBefore)
    {
        if(trigger.isupdate)
        {
            for(account ac: trigger.old)
            {
                List<opportunity> op =[Select name from opportunity where accountid = :ac.id]; 
                if(op.isEmpty())
                {
                    Opportunity opp = new opportunity(Name = 'First opportunity'+ ac.Name, Stagename ='Qualification',CloseDate = date.today(), accountid = ac.Id);
                    op.add(opp);
                }
                Else
                {
                    op.addError('This opportunity is already Exits');
                }
                insert op;
            }
        }
    } 
}
Khushmeet KaurKhushmeet Kaur
Hi Anik
Please try this code and let me know if you still face any error

trigger CheckOpportunitys on Account (after insert, after update) {
   List<Opportunity> opportunityList = new list<Opportunity>();
   List<Opportunity>opportunityInsertList = new List<Opportunity>();
   Set<id>accountId = new set<Id>();
  
    if(trigger.isInsert && trigger.isAfter){
       for(Account acc: trigger.New){
            opportunityList = [Select id,Name from Opportunity where accountId =:acc.Id];
            accountId.add(acc.Id);
       }
      if(opportunityList == NULL & opportunityList.isEmpty()){
         Opportunity opp = new opportunity(Name = 'First opportunity'+ ac.Name, Stagename ='Qualification',CloseDate = date.today(), accountid =                                           ac.Id);
         opportunityInsertList.add(opp);
      }
      else{
              system.debug('The opportunity already exist');
       }
     insert opportunityInsertList;
    }
}

for the update method please compare the trigger.old and trigger.new as if the opportunity updated or not from the previous value on Account