简体   繁体   中英

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. 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. 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. Your developer friends will thank you for avoiding the dreaded "SOQL 101" error.

So:

  1. Collect candidates for detailed check (all contacts that have the MailingStreet changed)
  2. Query them
  3. Loop through them again and smite if needed.

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');
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM