function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Oliver Jones RajkumarOliver Jones Rajkumar 

Help on Triggers

Hi All,

I'm a begginer in Apex Triggers. The following is a trigger I used but its not working. My Trigger should not allow ANY USERS to delete the record if the record creater (User) becomes INACTIVE. This trigger never allowed me to delete a record eventhough the User is active. Help n Thanks.

trigger  preventdelete  on  Loan__c (before delete){
    for(Loan__c  loan:Trigger.old){
          if(loan.CreatedBy.IsActive == FALSE ){
         loan.addError('You cant delete this record since it is created by an inactive user');
       }
     }
   }
Best Answer chosen by Oliver Jones Rajkumar
EldonEldon
Hi Oliver,

Please try this code. I have made the error to display on your custom object.
 
trigger DevtrgrCob on Loan__c  (before delete) {
   
    list<id> ids2 = new list<id>();
    for(Loan__c  p : trigger.old){
       
        ids2.add(p.id);
    }
    list<Loan__c > coblist = [select id,name,CreatedBy.isactive from Loan__c  where id in : ids2];
    for(Loan__c  p : trigger.old){
        for(Loan__c  c : coblist){
            if(p.id == c.id){
                if(c.CreatedBy.isactive == false){
                    p.addError('You cant delete this record since it is created by an inactive user');
                }
            }
        }
    }
}


Let me know if there is still any issues.
Please close the thread if it worked

Thankyou

All Answers

EldonEldon
Hi Oliver,

Try this code ,
 
trigger preventdelete on Loan__c (before delete) {
    //   trigger  preventdelete  on  Loan__c (before delete){
    
    list<id> ids = new list<id>();
    for(Loan__c p : trigger.old){
        system.debug('p'+p.CreatedByid);
        ids.add(p.createdbyid);
    }
    
    list<user> userlist = [select id,name,isactive from user where id in :ids];
    for(user u : userlist){
        system.debug('u.isactive'+u.isactive);
        if(u.IsActive == FALSE ){
            u.addError('You cant delete this record since it is created by an inactive user');
        }
    }
}

Let me know if you have any issues.

Mark it as best answer if it works.


Regards
salesforceMannsalesforceMann
Hello Oliver, 

I havent tried it, but the followign seems to be a visible issue:

Instead of 
loan.addError('You cant delete this record since it is created by an inactive user');

try:
trigger.oldmap.get(load.id).addError('You cant delete this record since it is created by an inactive user');

Let me know if it doesnt work. I will try it on my org then.
Thanks,
Mann.

Please mark as answer if you feel it is :)
 
Oliver Jones RajkumarOliver Jones Rajkumar
Hi Eldon,

Thanks. Your Code works accurately as per the scenario. Only problem is the error message thrown as below:

------
Validation Errors While Saving Record(s)
There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger preventdelete caused an unexpected exception, contact your administrator: preventdelete: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Trigger.preventdelete: line 14, column 1". 

Click here to return to the previous page.
------
salesforceMannsalesforceMann
@Eldon, (cc:Oliver)

You are using u.addError where u is a user instance. Wont this error be displayed on user? While required is to display error on Loan__c
Oliver Jones RajkumarOliver Jones Rajkumar
Hi Mann, 

I received an error message on compiling apex trigger code itself. 

--- Error: Compile Error: Variable does not exist: load.id at line 14 column 32 ---
salesforceMannsalesforceMann
@Oliver, its a typo mistake. 
Change it to loan.id
Salesforce####Salesforce####
hello eldon , 

the above code is throwing an error to me , where i slightly changed my scenario .  CAN YOU MODIFY MY CODE PLEASE 

scenario : i am using account object here , so a when ever account record is created by a user and if the user is made inactive and if other user is trying to delete it it should throw an error . 

my code : 
trigger DeleteRecord on Account (before delete) 
{
set<id> AcCreatedid = new set<id>();

for(Account acc :trigger.old)
  {
     system.debug('====acc.CreatedById====='+acc.CreatedById);
     AcCreatedid.add(acc.CreatedById);
  }

list<user> userlist = new list<user>([SELECT id ,name ,IsActive FROM User where id in:AcCreatedid ]);
  
 
for( user u:userlist )
  {
   if(u.IsActive == FALSE )
     {
      //User  userRecord = Trigger.oldMap.get(AcCreatedid);
       userRecord.addError('You cant delete this record since it is created by an inactive user');
     }
  }

}


getting error : There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger DeleteRecord caused an unexpected exception, contact your administrator: DeleteRecord: execution of BeforeDelete caused by: System.FinalException: SObject row does not allow errors: Trigger.DeleteRecord: line 19, column 1". 

in google i checked how to resolve it : http://www.srinivas4sfdc.com/2013/12/systemexception-sobject-row-does-not.html


 
EldonEldon
Hi Salesforce####,

Please post it as another thread . I will look into into it.

Regards
EldonEldon
Hi mann and Oliver,

Before triggers does not have access to values that are set by database on after insert(such as Created By, Created Date, Modified By, Modified Date etc.).

Regards
salesforceMannsalesforceMann
@Eldon, But the records are already in the database, so before trigger will have access in the case of isDelete and isUpdate.
Oliver Jones RajkumarOliver Jones Rajkumar
Hi Mann,

Now I got an error like this ---
User-added image
Salesforce####Salesforce####
eldon , the trigger is same , where i used for account as i havent created loan__C 
 
salesforceMannsalesforceMann
Hello Oliver,
It looks like I will have to get my hands dirty.
 Alllow me some time and I will create the trigger , test it on dev org and paste it here.

THANKS for being patient.
EldonEldon
Hi Oliver,

Please try this code. I have made the error to display on your custom object.
 
trigger DevtrgrCob on Loan__c  (before delete) {
   
    list<id> ids2 = new list<id>();
    for(Loan__c  p : trigger.old){
       
        ids2.add(p.id);
    }
    list<Loan__c > coblist = [select id,name,CreatedBy.isactive from Loan__c  where id in : ids2];
    for(Loan__c  p : trigger.old){
        for(Loan__c  c : coblist){
            if(p.id == c.id){
                if(c.CreatedBy.isactive == false){
                    p.addError('You cant delete this record since it is created by an inactive user');
                }
            }
        }
    }
}


Let me know if there is still any issues.
Please close the thread if it worked

Thankyou
This was selected as the best answer
salesforceMannsalesforceMann
Hello Oliver, 

Here is the working and tested code: (am working on account object, so replace it with your Loan object)
 
trigger preventdelete on Account (before delete) {
    
    //get all user list with active status
    List<user> u_lst = new List<user>([select id,isActive from user]);
    //create map
    Map<Id,Boolean> u_id_isActive = new Map<Id,Boolean>();
    for (user u : u_lst) {
        u_id_isActive.put(u.Id,u.isActive);
    }
    
    for(account a : trigger.old) {
        system.debug('a = '+a+' isactive = '+a.CreatedBy.IsActive);
        if(u_id_isActive.get(a.CreatedById)) {
            
            system.debug('yes active - ');
            a.addError('cannot delete');
        }
        
    }

}

Here is the screenshot of output as expected:
User-added image


This will work :)

Kindly mark as answered.
Thanks.
 
salesforceMannsalesforceMann

And here is the reason why your code did not work.

When accessing createdby.isactive, it always results in false!!

I am not sure why salesforce behaves this way 

Oliver Jones RajkumarOliver Jones Rajkumar
Thank you Mann and Eldon!! Both of your Triggers worked. Thanks for sharing your precious time for me.
Salesforce####Salesforce####
hi Mann and eldon , 

thanks both for helping , is this the correct output which we are getting for the above trigger ???? can you correct me  

error
 
EldonEldon
It should display the message we give in the adderror method.
 
Salesforce####Salesforce####
i am getting like above , but on the accout record , if i delete the account record i am getting thatmessage ,!!!! tell me whether it is the expected output 
salesforceMannsalesforceMann
Hi salesforce.. you seem to have some validations on ur sccount object. disable them plz
EldonEldon
You put your question in a new thread with your codes and requirement then only others can help you.
 
salesforceMannsalesforceMann
Hi oliver..no problem at all.
one question: was this question for your own benefit of learning or was it for a live scenario in your company?
salesforceMannsalesforceMann
Oliver, may I also request you to atleast  like my answer if it works as well. I am only asking because of the time I spent solving :)

 
Salesforce####Salesforce####
hi mann,

i dont have any validation rules on account object , i just checked 
Oliver Jones RajkumarOliver Jones Rajkumar
Ha Ha Ha liked all :)))) This scenario was given as per SF training today. And this scenario has been achieved through Sharing Settings. Surprised Though!
salesforceMannsalesforceMann
Hahaha. superb. enjoy salesforce till the next time! !