[英]Apex Trigger to update the value of Related to company field ( if it is null only) on the task object based on the related to contact
[英]Apex Trigger- Not reading null/blank field
尝试在 Apex 中创建触发器,如果联系人与客户相关并且在该关系中具有定价信函角色。 如果存在 Pricing Letter 关系,用户将无法删除联系人 object 上的 Mailing Street。每次我尝试更改 Mailing Street 时都会触发以下内容,即使它不是空白。 有任何想法吗?
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```
如果您有一个空街道的联系人并且您的代码运行为“更新前”并且您从数据库中查询该联系人 - 它仍然具有旧的空白值,尚未保存任何内容。 我怀疑这就是它抛出错误的原因。
分 3 个步骤完成它是“良好的形式”,只有在您知道绝对必须时才运行查询。 您的开发人员朋友会感谢您避免了可怕的“SOQL 101”错误。
所以:
像这样的东西(不保证它会编译):
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.