You need to sign in to do that
Don't have an account?
PRADEEP 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
{
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
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!
Hope that solves your issue. Please mark the answer as best answer if I could have help!