[英]Apex Trigger- Not reading null/blank field
Trying to create a Trigger in Apex where if the Contact is related to an Account and has a Pricing Letter role on that relationship.尝试在 Apex 中创建触发器,如果联系人与客户相关并且在该关系中具有定价信函角色。 If there is a Pricing Letter relationship, the user should not be able to delete the Mailing Street on the Contact object. The below fires every time I try to change the Mailing Street even if it not blank.
如果存在 Pricing Letter 关系,用户将无法删除联系人 object 上的 Mailing Street。每次我尝试更改 Mailing Street 时都会触发以下内容,即使它不是空白。 Any ideas?
有任何想法吗?
List<Contact> relatedcontacts = new list<Contact>([SELECT id,mailingstreet FROM Contact WHERE id IN(SELECT ContactId
FROM accountcontactrelation
WHERE roles INCLUDES ('Pricing Letters')) AND id IN : Trigger.new]);
for(Contact c : relatedcontacts){
if(c.MailingStreet==null){
Contact con = Trigger.newMap.get(c.id);
con.addError('Mailing Street on Pricing Letter Contacts cannot be null');
}//End If Statement
}//End For Loop
}//End Class```
If you have a Contact with empty street and your code runs as "before update" and you query that contact from database - it'll still have old blank value, nothing's saved yet.如果您有一个空街道的联系人并且您的代码运行为“更新前”并且您从数据库中查询该联系人 - 它仍然具有旧的空白值,尚未保存任何内容。 I suspect that's why it throws you the error.
我怀疑这就是它抛出错误的原因。
It's "good form" to do it in 3 steps, run query only if you know you absolutely have to.分 3 个步骤完成它是“良好的形式”,只有在您知道绝对必须时才运行查询。 Your developer friends will thank you for avoiding the dreaded "SOQL 101" error.
您的开发人员朋友会感谢您避免了可怕的“SOQL 101”错误。
So:所以:
Something like this (no promises it'll compile):像这样的东西(不保证它会编译):
trigger ContactTrigger on Contact (before update){
Set<Id> candidates = new Set<Id>();
// 1
for(Contact c : trigger.new){
Contact old = trigger.oldMap.get(c.Id);
if(c.MailingStreet == null && old.MailingStreet != null){
candidates.add(c.Id);
}
}
// 2
if(!candidates.isEmpty()){
Set<Id> check = new Map<Id, Contact>([SELECT Id
FROM Contact
WHERE Id IN :candidates
AND Id IN (SELECT ContactId FROM AccountContactRelation WHERE Roles INCLUDES ('Pricing Letters'))
]).keyset();
// 3
for(Id i : check){
trigger.newMap.get(i).addError('Mailing Street on Pricing Letter Contacts cannot be null');
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.