-1
trigger RestrictHindiTeacher on Teach__c(before insert, before update) {
    if(trigger.IsInsert){
        for(Teach__c c : trigger.new){
            if(c.subject__c.contains('Hindi')){
                c.subject__c.addError('Sorry Hindi teachers can not create the account');
            }
        }
    }
    else {
        for(Teach__c c : trigger.old){
            if(c.subject__c.contains('Hindi')){
                c.addError('Sorry Hindi teachers can not update the account');
            }
        }
    }
}

enter image description here

**When subject is Hindi record can not be updated **that's my concern

Please help how I can solve this issue

2 Answers 2

0

You can use the addError method for only those records that are avaliable in Trigger Context . I think we can use Trigger.newMap for before insert and before update. and Trigger.oldMap for before delete

trigger RestrictHindiTeacher on Teach__c(before insert, before update) { if(trigger.IsInsert){ for(Teach__c c : trigger.new){ if(c.subject__c.contains('Hindi')){ c.subject__c.addError('Sorry Hindi teachers can not create the account'); } } } else { for(Teach__c c : trigger.old){ if(c.subject__c.contains('Hindi')){ Teach__c actualRecord= trigger.newMap.get(c.Id); actualRecord.adderror('Sorry Hindi teachers can not update the account'); } } } }

0

You don't need the else part. Try below.

trigger RestrictHindiTeacher on Teach__c(before insert, before update) {
if(trigger.IsInsert || trigger.IsUpdate){
    for(Teach__c c : trigger.new){
        if(c.subject__c.contains('Hindi')){
            c.addError('Sorry Hindi teachers can not create the account');
        }
    }
}}
5
  • But in this case, if I update the field of Teach__c then it will not show any error. I want that for all Hindi related cases it restrict to create and update
    – Gopal
    Apr 26, 2020 at 3:55
  • It will throw an error , that's why we are using trigger.IsUpdate in the OR condition. Why don't you give a try and see what it gives. Apr 26, 2020 at 4:16
  • c.addError('Sorry Hindi teachers can not update the account'); But this line is always throwing an exception, Is there any alternative to print the error on UI
    – Gopal
    Apr 26, 2020 at 4:56
  • Updated my answer. adderror() is always called in the trigger's record context. But it seems you were using in the field context c.subject__c.addError('Sorry Hindi teachers can not create the account'); which is incorrect Apr 26, 2020 at 6:21
  • @gopal :- If that resolves your error message. Can you close this thread by selecting an answer. Apr 26, 2020 at 18:45

You must log in to answer this question.

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