触发器以防止 salesforce 中出现重复的记录名称
我需要防止输入重复的名称。需要使用触发器来施加此限制。我想知道如何限制 DML 操作的发生。不确定批量代码中 .addError 的用法。
Set<string> Seta= new Set<string>();
for(oj__c o:trigger.new)
{
Seta.add(c.name);
}
List<oj__c> listoj= new List<oj__c>();
listoj=[select id from oj__c where name in :Seta]
if listoj.size()>0
trigger.new.adderror('Cannot have duplicate name');// i know this line is wrong. How can i stop the DML statement from excuting?
I need to prevent duplicate names from been entered. This restriction needs to be imposed using a trigger. I want to know how i can restrict the DML operations from happening. Not sure of the usage of .addError in bulkified code.
Set<string> Seta= new Set<string>();
for(oj__c o:trigger.new)
{
Seta.add(c.name);
}
List<oj__c> listoj= new List<oj__c>();
listoj=[select id from oj__c where name in :Seta]
if listoj.size()>0
trigger.new.adderror('Cannot have duplicate name');// i know this line is wrong. How can i stop the DML statement from excuting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以在这里找到我正在寻找的内容的一个很好的参考。
http://www.salesforce.com/docs/developer/cookbook/Content /apex_dedupe.htm
A good reference to what i was looking for could be found here.
http://www.salesforce.com/docs/developer/cookbook/Content/apex_dedupe.htm
您可以将 addError 与单个记录一起使用,然后这些记录应该在数据加载器的报告中显示,但如果您想停止所有内容,那么您也可以抛出异常。
You can use addError with individual records which should then show against them on the report in dataloader, though if you want to stop everything where it is then you can also just throw an exception.
您的代码有一个错误,即它不会发现当前批次中的重复项,例如,将通过 API 插入 5 行相同名称的行。
执行此操作的一种更简单的方法是让触发器将名称字段复制到自定义字段,然后在自定义字段定义中将其设置为唯一。
You code has a bug in that it won't spot dupes within the current batch, e.g. an API insert of 5 rows all the same name will go through.
An easier way to do this, is to just have your trigger copy the name field to a custom field, and then in the custom field definition set it to be unique.