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
Assaltu RDAssaltu RD 

How to avoid updating records with a trigger.

Hi Guys ! 
I want to avoid with a trigger that a user who is not a system administrator can change the status of a case. 
Best Answer chosen by Assaltu RD
Steven NsubugaSteven Nsubuga
trigger CaseStatusCheck on Case (before update)
{
	String ProfileId = UserInfo.getProfileId(); 
	Profile systemAdminProfile = [select Id from Profile where name = 'System Administrator' LIMIT 1];
   
	for (Case cs : Trigger.new)     
	{           
		if (cs.status != Trigger.oldMap.get(cs.Id).status && ProfileId != systemAdminProfile.Id)
		{
			cs.addError('You do not have the rights to change the status of this case record');
		}
	}
}

 

All Answers

Raj VakatiRaj Vakati
You can create a Flag on the user level -and by pass the trigger if its true 
  1. Create a new flag at user level ( by pass trigger __c ) boolean 
  2. If its checked by pass the trigger logic 
Steven NsubugaSteven Nsubuga
trigger CaseStatusCheck on Case (before update)
{
	String ProfileId = UserInfo.getProfileId(); 
	Profile systemAdminProfile = [select Id from Profile where name = 'System Administrator' LIMIT 1];
   
	for (Case cs : Trigger.new)     
	{           
		if (cs.status != Trigger.oldMap.get(cs.Id).status && ProfileId != systemAdminProfile.Id)
		{
			cs.addError('You do not have the rights to change the status of this case record');
		}
	}
}

 
This was selected as the best answer
Assaltu RDAssaltu RD
Thank you so much guys! 
I did it this way

Regards!
 
trigger closedCase on Case (after insert, after update) {
	
    set<id> idC = new set<id>();
    for(Case c: Trigger.new){
        idC.add(c.LastModifiedById);
    }
    
    user us = [select id, profileId, name FROM user where id=: idC LIMIT 1];
    
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Case c: Trigger.new){
            if(c.status == 'Closed'){
                if(us.profileId != '00e1H000001XdcAQAS'){ // id profile system administrator
                    c.addError('You do not have the rights to change the status to closed');
                }      
            }
    	}
    }   
}