3 Objects —
Application
Auth Contact
AppAuthContact
AppAuthContact
is a Junction Object between Application
and Auth Contact
.
The fields in AppAuthCon
are ApplId
, AuthConId
and ContactId
.
I have requirement to create a trigger on User record when created.
- Find matching
Auth Contact
for newUser
using Email Auth Contact
found- Find all
AppAuthCon
forAuth Contact
. - Update all such
AppAuthCon
records and populate Contact — contact lookup to be populated using contact of that user - Remove
Auth Contact
record –deleting
Following is my trigger
trigger UserTrigger on User (after insert) {
UserTriggerMethod.updateApplicationEditor(trigger.oldMap, trigger.newMap);}
Following is apex class code called from trigger
public with sharing class UserTriggerMethod {
public static void updateApplicationEditor(Map<ID,User> mapOldUser,Map<ID,User> mapNewUser)
{
if(mapNewUser != null && !mapNewUser.isEmpty())
{
for(User user : mapNewUser.values())
{
Auth_Contact__c AuthContact = [SELECT Id
FROM Auth_Contact__c
WHERE Email__c = : user.Email LIMIT 1];
if(AuthContact ! = null)
{
List<App_Auth_Contact__c> lstAppAuthCon = [SELECT Contact__c
FROM App_Auth_Contact__c
WHERE Auth_Contact__c = : AuthContact.Id];
List<App_Auth_Contact__c> lstAppAuthContoupdate = new List<App_Auth_Contact__c>();
List<Auth_Contact__c> lstAuthContacttodelete = new List<Auth_Contact__c>();
for(App_Auth_Contact__c AppAuthCon: lstAppAuthCon)
{
AppAuthCon.Contact__c = user.ContactId;
lstAppAuthContoupdate.add(AppAuthCon);
}
lstAuthContacttodelete.add(AuthContact);
}
}
}
if(lstAppAuthContoupdate.size() > 0)
{
try
{
update lstAppAuthContoupdate;
}
catch(DMLException e)
{
system.debug(e.getMessage());
}
}
if(!lstAuthContacttodelete.IsEmpty())
{
delete lstAuthContacttodelete;
}
}
}
Issues faced:-
- How do i check that delegated contact exist
if(AuthContact ! = null)
— giving error when i save
Best Answer
As @sfdcfox noted, your immediate issue was
! =
should be!=
. However, you have several other issues, ranging from additional compile-time errors to inefficient code to bad practices which really should be addressed.Here's what I see:
trigger.oldMap
to an insert handler; it will always be null (there are no 'old' values for an insert). See Trigger Context Variables in the Apex Programmers guide for more. If you plan to expand this trigger handler for updates, you can add it back for testing if the user's email has changed.mapNewUser
for null or empty; the insert trigger won't be called if there are no new User records being inserted. If you expand the trigger handler for updates, you will need to check if oldMap is null.lstAppAuthContoupdate
andlstAuthContacttodelete
inside a block, but try to use them outside the block. This will result in additional compile time errors.Here's a reworked version of your code, using only one SOQL query and using maps to avoid the need for more queries. Note that you'll have to update your trigger to only pass trigger.newMap.