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

How to trigger a php function for custom server side form validation?


Go to End


2 Posts   2426 Views

Avatar
Tama

Community Member, 138 Posts

20 September 2010 at 1:57pm

Howdy

I've been searching around the forums and documentation for a while but am still a bit lost about this. I've got a form which I want to validate server-side by using my own php function.

There's the "php" method in the RequiredFields class: http://api.silverstripe.org/2.4/forms/validators/RequiredFields.html - but I can't find any example of how this would work in the wild.

On the most basic level I'm looking for an example of how to get something like the code to work. This is where a value from a TextField is sent to a function which then returns a message and either does or doesn't validate the field.

$fields = new FieldSet(
    new TextField('Number', 'Enter a Number', '' )
);

function ValidateNumber($Number){
    if($Number == 10){
        $Message = "You have entered the right number";
        $Validate = true;
    } else {
        $Message = "You have entered the wrong number, try again";
        $Validate = false;
    }
}

Can someone please show me an example of how this would work inside the sapphire framework?

Cheers
Tama

Avatar
swaiba

Forum Moderator, 1899 Posts

1 October 2010 at 2:20am

Edited: 01/10/2010 2:20am

Does this help? (from one of my forms with validation)...


class MyFormPage_Controller extends Page_Controller
{

	function MyForm()
	{
		$fields= new FieldSet(
			new TextField('MyTextField')
		);


		$actions = new FieldSet(
			new FormAction('ProcessFrom', 'Join')
		);

		$validator = new RequiredFields(
			'MyTextField'
		);

		$form = new Form($this, 'MyForm', $fields, $actions, $validator);
		
		if(Session::get("MyFormData"))
		{
			$previous_value = Session::get("MyFormData");
			Session::clear("MyFormData");
			$form->loadDataFrom($previous_value);
		}

		return $form;
	}
	


	function ProcessFrom($data,$form)
	{
		$bValid = true;
		
		Session::set("MyFormData", $data);

		if($data['MyTextField'] != 'somevalue')
		{
			$form->addErrorMessage('MyTextField','MyTextField is not "somevalue"','required');
			$bValid = false;

		}

		if (!$bValid)
		{
			//failed validation
			return Director::redirectBack();
		}

		//passed validation
		
		//do stuff with form data
		
		return Director::redirect(Director::baseURL(). $this->URLSegment.'?posted=1');
	}
}