I think your trigger is pretty close to what you're looking for, you just don't have the correct conditions in your if
statement.
Right now, your code says "prevent deletion (by adding an error) when deleted__c is false and Ninja_Store_Id__c is not an empty string"
An empty string is not the same as blank. Salesforce doesn't store completely empty strings ''
in SObject records (except, and instead converts the value to null
. null != ''
).
Salesforce gives us String.isBlank()
and String.isNotBlank()
to handle such situations.
Also, <boolean value> == true
can be reduced to simply <boolean value>
.
Likewise, <boolean value> != true
can be reduced to !<boolean value>
.
So given what you've told us, your if
statement should be
if(!acc.deleted__c && String.isNotBlank(acc.Ninja_Store_Id__c))
Running through the various possible scenarios, writing down what they are and what result they give (not what you want to happen, what actually does happen given the code you have) can be a helpful tool. If I were to do that, this is what that would look like:
- deleted__c == true
- then the first condition is false. false && anything = false, so we don't need to evaluate the other condition
- don't enter the
if
block.
- Deletion is allowed
- deleted__c == false, Ninja Store is blank.
- we satisfy the first condition
- Ninja Store is blank, so the second condition results in false
- true && false = false, so we don't enter the
if
block
- Deletion is allowed
- deleted__c == false, Ninja Store has a value
- Both conditions are satisfied, and we enter the
if
block
- Deletion is not allowed