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
  • 1
    I would advise <apex:pageMessages/> Commented Aug 14, 2018 at 15:13

2 Answers 2

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}"/>
2
  • Thanks, that was the issue. I knew it was going to be some dumb error on my part. Commented Aug 14, 2018 at 15:45
  • 2
    I've been there too - sometimes you just need an extra set of eyes! Commented Aug 14, 2018 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.

2
  • 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. Commented Aug 14, 2018 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. Commented Aug 14, 2018 at 15:16

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.