0

What I'm trying to do is that when a checkbox is true, my rich-text area is required to have image but when I run this code, it still can proceed even no image in that rich-text area.

Kindly help me to fix this :(

my checkbox: TSM_Email__c
my rich text area: Attachment__c

So here is my current code and it pop out this error message.. is there any problem with my code?

trigger PraTrigger on I4_0_Project_Request_And_Approval__c (before insert, before update) {
    for (I4_0_Project_Request_And_Approval__c p:Trigger.new){
        
        String picString = p.Attachment__c.substringBetween('<img', 'img>');
        if((p.TSM_Email__c == true) && (picString == null)){
                p.addError('Picture is required to proceed');
            }
            
        }
    }

enter image description here

3
  • Based on that trigger logic, any I4_0_Project_Request_And_Approval__c record would throw an error when updated. Have you tried adding any sort of debugging to see if the trigger code is being fired at all? Jul 8 at 3:03
  • Is this the full code of the logic? Because you have added addError in both if and else, so practically any updation on the record should fail. Jul 8 at 4:22
  • Yes, this is the full code but i have amended a bit.. adding before insert and it fired my code but if didnt put any image in the rich text, i come out an error from the code execution.. can see it in my edited code Jul 8 at 13:46
0

If Attachment__c is null/blank, your code will throw a NullPointerException. You need to check that there's any value in the field before checking if it contains/does not contain a certain string/value. Not to mention, if it is null (which means it has no img) - you need to also add the error. In other words, you have 2 conditions to check where you want an error

  1. if the checkbox is true and the rich text is not filled out at all - add error
  2. if the checkbox is true and the rich text is filled out without an image - add error

In code, it looks like this where you can make use of String.isBlank

for (I4_0_Project_Request_And_Approval__c p:Trigger.new){
    if(p.TSM_Email__c && (String.isBlank(p.Attachment__c) || (String.isNotBlank(p.Attachment__c) && !p.Attachment__c.contains('<img')))){
        p.addError('Picture is required to proceed');
    }
            
}
 
3
  • Hi Kris, I've tried this one but it doesnt fire this logic.. i can save when i checked the box even got no image Jul 13 at 8:03
  • I updated it to handle the scenario you're actually testing which is filling out nothing in the Attachment__c field. Jul 13 at 13:41
  • Hi Kris. It works!! Thank you so much for your help! Much appreciated >< Jul 15 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.