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.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Form Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Global error message if custom form fails validation...


Go to End


3 Posts   2977 Views

Avatar
vwd

Community Member, 166 Posts

12 February 2014 at 11:55pm

Edited: 12/02/2014 11:56pm

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

Community Member, 166 Posts

14 February 2014 at 3:04pm

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;
	}
}

Avatar
theruss

Community Member, 3 Posts

20 December 2016 at 10:05pm

Legend.

I have very little hair left to pull out, but this seemingly insane workaround did the trick. The Form class should really have some way to intercept its internal validation routine.