4

I'm new to the world of Apex and have managed to cobble together this code that looks at a particular field and prevents deletion of that record if a particular field (in this case 'Data Source' isn't empty/null.

Although the code below works, it will prevent deletion if the field has any value in it and I need to customise it so that if a particular word is in that field, only then will it block deletion. But when I tried to specify this using code like "IBIS" (the name of an internal system I'm targetting), I got errors about incorrect data type.

Is what I'm trying to achieve possible?

My trigger code:

trigger IBISAccountDeleteTrigger on Account (before delete) {
    for(Account acc : trigger.old){
        if(acc.Data_Source__c != null)
            acc.adderror('Sorry, we cannot delete this record as it came from IBIS.');
        }
    }

Data_Source__c is a Text field btw.

Thanks in advance :-)

3
  • 2
    What was the if statement that you tried to use when comparing Data_Source__c to 'IBIS'? You can edit your question to include that information.
    – Derek F
    Jan 21 at 17:06
  • And I'll say, we seem to have some vigorous downvoters today.
    – Derek F
    Jan 21 at 17:07
  • 1
    Yeah, I'm not sure I agree with the downvotes here - if you can show us the code you tried that was not successful this post will have all the ingredients of an excellent first question. Welcome to SFSE.
    – David Reed
    Jan 21 at 17:21

1 Answer 1

4
//You can use the following

 for(Account acc : trigger.old){
        if(acc.Data_Source__c != null && acc.Data_Source__c.contains('IBIS')){
            acc.adderror('Sorry, we cannot delete this record as it came from IBIS.');
        }
 }

//if caps does not matter you can use the containsIgnoreCase(substring)

Refer to https://developer.salesforce.com/docs/atlas.en-us.234.0.apexref.meta/apexref/apex_methods_system_string.htm

2
  • 1
    Close, but remember to check for nulls before calling an instance method.
    – sfdcfox
    Jan 21 at 17:25
  • awesome thanks!
    – Asheer
    Jan 21 at 17:30

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.