+ Start a Discussion
Carlos  Jesus Ramos FragosoCarlos Jesus Ramos Fragoso 

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 Carlos Jesus Ramos Fragoso
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
Carlos  Jesus Ramos FragosoCarlos Jesus Ramos Fragoso
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');
                }      
            }
    	}
    }   
}