function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Robert Lange 4Robert Lange 4 

I have been trying to write an Apex trigger that displays an error message on the Account record if the user enters Baltimore for BillingCity. Any thoughts? Here is the code I am trying to use:

trigger BaltimoreNo on Account (before insert) {
    for (Account acc : Trigger.new){
        if (acc.BillingCity='Baltimore'){
            alert ('Company XYZ will not do business in city of Baltimore');
     
        }
    }
}
Best Answer chosen by Robert Lange 4
Ashish Singh SFDCAshish Singh SFDC
Hi Robert,

The problem here is you're using '=' operator which is assignment operator instead of this you need to use comparision operator '==' and additionally you need use addError() method here. alert is a Javascript command to show popup on browser.

And yes as Devi & Manto said, you should use available functionality. But it seems like you're new to development and you're practising in you Dev Org.

Please try below code:
 
trigger BaltimoreNo on Account (before insert) {
    for(Account acc: Trigger.new){
        if(acc.BillingCity == 'Baltimore'){
            acc.addError('Company XYZ will not do business in city of Baltimore');
        }
    }
}


Best Regards,
Ashish Singh.

All Answers

Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi robert,
No need of trigger for this.You can simply create a validation rule.
Give the following formula in validation rule condition
BillingCity = 'Baltimore'

As a best practice always go for configuration whenever possible without writing code.

Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards
 
MantoManto
Ageed to Devi. click before code. 
And for any reason if you still want to write apex: replace your alert(...) with acc.addError('...');
Ashish Singh SFDCAshish Singh SFDC
Hi Robert,

The problem here is you're using '=' operator which is assignment operator instead of this you need to use comparision operator '==' and additionally you need use addError() method here. alert is a Javascript command to show popup on browser.

And yes as Devi & Manto said, you should use available functionality. But it seems like you're new to development and you're practising in you Dev Org.

Please try below code:
 
trigger BaltimoreNo on Account (before insert) {
    for(Account acc: Trigger.new){
        if(acc.BillingCity == 'Baltimore'){
            acc.addError('Company XYZ will not do business in city of Baltimore');
        }
    }
}


Best Regards,
Ashish Singh.
This was selected as the best answer
Robert Lange 4Robert Lange 4
Ashish et al., I am new to Apex so I am getting practice.  Thank you very much for your responses!