0

I'm trying to write an apex trigger that before delete checks the user's profile and a custom field called ID_Prestige__c. If the field is empty you can't delete the account object. Only if you have the rank of System Administrator you can.

trigger DeleteAccount on Account (before delete) {
    Id profileId = UserInfo.getProfileId();
    profile profileName = [SELECT Name FROM Profile WHERE id=:profileId];
    
    for(Account dupAccount : Trigger.old){
        if(profileName.Name != 'System Administrator' && dupAccount.ID_Prestige__c != null){
            dupAccount.addError('You can't delete this account: You don't have the rank of System Administrator or the fiel ID_Prestige contains a value');
        }
    }
}

I don't know if what i've done makes sense and i don't know how to test it in the anonymous window. However, this isn't exactly what i've been asked to do, as they've asked me to make a trigger handler and a method inside it to call it on the trigger. I don't know how to make it that way. Thanks for the help.

1 Answer 1

1

As per this If the field is empty you can't delete the account object. Only if you have the rank of System Administrator you can.

You need to check if ID_Prestige__c is null, then stop account deletion, only allow deletion if System Administrator is executing.

You can create a RestrictAccountDeltion class something like this. This becomes your handler.

public class RestrictAccountDeletion {

    public void restrictAccountValidationBasedOnFieldValue(List<Account> accountList) {
        Id profileId = UserInfo.getProfileId();
        Profile profileName = [SELECT Name FROM Profile WHERE Id = :profileId];

        for (Account dupAccount : accountList) {
            if (dupAccount.ID_Prestige__c == null && profileName.Name != 'System Administration') {
                dupAccount.addError('You can\'t delete this account: You don\'t have the rank of System Administrator or the field ID_Prestige contains a value');
            }
        }

    }

} 

And from trigger remove your code and call this method.

trigger AccountTrigger on Account (before delete) {
    RestrictAccountDeletion.restrictAccountValidationBasedOnFieldValue(Trigger.old);
}

YOu can change this logic as per your wish. if (dupAccount.ID_Prestige__c == null && profileName.Name != 'System Administration') but as you have written If the field is empty you can't delete the account object. thus I have changed this.

1
  • oh yeah i wrote that wrong, thanks for your help. Jul 1, 2022 at 12:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .