Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Form Questions

Global error message if custom form fails validation...


Reply

2 Posts   456 Views

Avatar
vwd

12 February 2014 at 11:55pm (Last edited: 12 February 2014 11:56pm), Community Member, 159 Posts

Hi,

I'm trying to use MathSpamProtection in a custom form which happens to be very long.

When the server side form validation fails (e.g. required field not filled, invalid value or spam protection fails) the error message is attached to the field. Since the form is very large and the MathSpamProtectionField is at the bottom, if the spam protection validation fails, they may not notice the error message and assume that the submission was successful. So I'd like to set the global error message (which is at the top of the form in this case) to alert them that something is amiss.

A couple of questions:

  • 1) How (& where) can I also set a global error message upon the spam protection validation failure?
  • 2) Do I have the extend Form to achieve this or I can I do it in the page controller in which the submission handler is present?

Thank you.
VWD.

Avatar
vwd

14 February 2014 at 3:04pm Community Member, 159 Posts

For others who may be trying to achieve this the solution was to extend Form and override the validate() function:

<?php
class GlobalMessageOnErrorForm extends Form {
   public function validate(){
      if($this->validator){
         $errors = $this->validator->validate();

         if($errors){
            $this->sessionMessage('Please correct errors and resubmit', 'error');   // set global error message here

            // Load errors into session and post back
            $data = $this->getData();
            Session::set("FormInfo.{$this->FormName()}.errors", $errors);
            Session::set("FormInfo.{$this->FormName()}.data", $data);
            return false;
         }
      }
      return true;
   }
}