1

I am trying to add a custom error message to a VF page. My controller saves, but when I save my VF page without the checkbox field being checked, it saves anyway and bypasses the error condition in my controller. What am I doing wrong?

VF Page:

<apex:page standardController="Quote__c" extensions="QuoteExtController">
<apex:messages/>
<apex:form >
    <apex:commandButton value="Save" action="{!save}"/>
    <apex:pageblock>
        Quote Name: <apex:InputField value="{!Quote__c.Name}"/>
        Quote Check: <apex:InputField value="{!Quote__c.Must_Be_Checked__c}"/>
    </apex:pageblock>
</apex:form>
</apex:page>

Controller Extension:

public with sharing class QuoteExtController {
    private quote__c quote;

    public QuoteExtController(ApexPages.StandardController stdController) {
        this.quote = (Quote__c)stdController.getRecord();
    }

    public PageReference onSave() {
        if(quote.Must_Be_Checked__c==TRUE) {
            ApexPages.Message myMsg = new  ApexPages.Message(ApexPages.Severity.ERROR,'Check field');
            ApexPages.addMessage(myMsg); 
            return null;
        } else if (quote.Id != null) {
            insert quote;
        }

        return null;
    }
}
  • 1
    I would advise <apex:pageMessages/> – gNerb Aug 14 '18 at 15:13
5

Your command button is calling the standard controller save. You need to use your custom action in the save button, shown below:

<apex:commandButton value="Save" action="{!onSave}"/>
| improve this answer | |
  • Thanks, that was the issue. I knew it was going to be some dumb error on my part. – J. Neilan Aug 14 '18 at 15:45
  • 2
    I've been there too - sometimes you just need an extra set of eyes! – battery.cord Aug 14 '18 at 17:01
0

It's because you're using Quote__c in your page, and not your quote page property.

Change your VF markup to use this:

<apex:pageblock >

  Quote Name: <apex:InputField value="{!quote.Name}"/>
  Quote Check: <apex:InputField value="{!quote.Must_Be_Checked__c}"/>
</apex:pageblock>

And finally, make sure you're calling your custom onSave method and not the standard Save method.

| improve this answer | |
  • 2
    That call to addFields is not valid syntax. Quote__c and Quote as shown here are referring to the same object instance, which should have those fields populated due to their use in the body of the Visualforce page. – David Reed Aug 14 '18 at 15:15
  • I agree it's kinda weird that they are using a custom object for quote but I don't think that's the root of the issue and there very well may be a reason for it. I'd advise sticking to the topic at hand. – gNerb Aug 14 '18 at 15:16

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.