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
PRADEEP YADAV 5PRADEEP YADAV 5 

Trigger Context Variable not Insert the Record or not Update

trigger Trigger1Problem on Account (after Insert, after Update)
{
    if(Trigger.isAfter)
    {
            if(Trigger.isInsert)
            {
                List<Opportunity>opp = new List<Opportunity>();
    
                Map<Id, Account>mapacc = new Map<Id, Account>
                ([Select Id, Name,(Select Id, Name From Opportunities) From Account Where Id In :trigger.new]);
    
            for(Account acc : trigger.new)
                {
                    if(mapacc.get(acc.Id).Opportunities.size() == 0)
                        {
                            opp.add(new Opportunity(AccountId =acc.Name, Name ='FirstOpportunity'+acc.Name, StageName = 'prospecting'
                            , CloseDate = System.today()));
                        }
                }
                insert opp;

            }
            else
            {
                if(Trigger.isUpdate)
                {
                    Map<Id, Account> nMap = new Map<Id, Account>();
                    
                    nMap = Trigger.newMap;
                    
                    List<Opportunity>opp = [Select Id, Name From Opportunity Where
                    Id In : nMap.keySet()];
                    
                    for(Opportunity oppup : opp)
                    {
                        Account a = nMap.get(oppup.Id);
                        
                        oppup.Name = a.Name;
                    }
                    update opp;
                }
            }
    
    }
    
}
no error but not inserted or not updated record doing this question 
1) context variable 
2) Helper class
Nikhil_KhetanNikhil_Khetan
@PRADEEP

1. This is not an ideal way of writting trigger, i would suggest look at concept of interface or atleast Trigger handlers.
2. In your insert, instead of check size = 0, can you check null? Or add a OR condition along with size() to check the null?
3. In your update, you made a query on opportunity with ID In Trigger map, but here the trigger is context of account,
shouldn't it be Account Id In: nMap.keySet() ?

Regards,
Nikhil
Please mark this as best answer, if my answer helped!
PRADEEP YADAV 5PRADEEP YADAV 5
Thanks Nikhi_Khetan
Nikhil_KhetanNikhil_Khetan
@Pradeep
Hope that solves your issue. Please mark the answer as best answer if I could have help!