You need to sign in to do that
Don't have an account?
Anil Meghnathi
Insert record not working when I addError in a trigger
hi pat
i have a problem.
I have a sobject TestStoring__c with one custom field Body__c.In after insert trigger on FeedItem , when i insert a record in
TestStoring__c sobject,it is not getting inserted.I am also attaching the code below.
Class:
public class TestTriggerClass { public static string flag; public static void addFeedError(list<FeedItem> fi) { if(fi[0].body.contains('blocked')) { flag='not'; fi[0].adderror('Not Allowed'); return; } else { flag='done'; return; } } }
Trigger:
trigger Test on FeedItem (after insert) { FeedItem[] f=Trigger.New; TestTriggerClass.addFeedError(f); System.debug(TestTriggerClass.flag); if(TestTriggerClass.flag!='done') { TestStoring__c vv=new TestStoring__c(); vv.Body__c=f[0].body; insert vv; } }
Any idea will help me.
Thanks
Anil
Unfortunately, it is not possible to insert records, call future methods etc when you use addError - see this answer.
Thanks Pat
I have used future call as per your kind suggestion for insertion of the object.But still its not getting inserted.Even they are not calling the future method updateAccount(String body) .Any idea??Any suggestion will be helpful to me.
Class:AccountUpdater
public class AccountUpdater
{
@Future(callout=true)
public static void updateAccount(String body)
{
System.debug(body);
TestStoring__c vv=new TestStoring__c();
vv.Body__c=body;
insert vv;
}
}
Trigger:
{
FeedItem[] f=Trigger.New;
TestTriggerClass.addFeedError(f);
System.debug(TestTriggerClass.flag);
if(TestTriggerClass.flag!='done')
{
AccountUpdater.updateAccount('body');
}
}
Class:TestTrigger
public class TestTriggerClass
{
public static string flag;
public static void addFeedError(list<FeedItem> fi)
{
if(fi[0].body.contains('blocked'))
{
flag='not';
fi[0].adderror('Not Allowed');
return;
}
else
{
flag='done';
return;
}
}
}
Any suggestions??
On further research, it looks like all DML, future calls etc in the current transaction are rolled back when addError is called. The only record of the error is in the system log.
The addError() method used when you want to stop or roll back the DML call if some condition is met or not. And also display the error messaage on field or object.
So in your case if you want that the error come but stil the DML call should perform then don't use addError() method for this requirement.
For your solution create a custom form by using lightning component or visualforce then check the the condition in apex or javascript code on submit then if you want to show some error then you can simply show it and also you can perform the DML call with that.
In case you find any other issue please mention.
If you find your Solution than mark as this as a best answer.
Thanks and Regards
Suraj Tripathi.