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 /

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

[SOLVED] Repopulate fields after custom validation

Go to End

3 Posts   1939 Views


Community Member, 12 Posts

2 April 2014 at 4:50pm

Edited: 02/04/2014 4:52pm

I'm dynamically adding fields to a form, and validating that at least one of them has been completed.
However once the validation has completed, and redirectBack() has occurred, none of the posted fields have their values any more.

I've found a couple of posts ( and which indicate that calling Session::set('', $data); before return $this->redirectBack(); should resolve the problem, but it's not working. Perhaps this is for an older version, I'm running 3.1.3.

The complete code is as follows:

        public function Cart() {
			$tests = TestPage::get();

			$fields = new FieldList(

			foreach ($tests as $test) {
					NumericField::create('test' . $test->ID, $test->Title)
						->setAttribute('type', 'number')

			$validator = new RequiredFields(

			$actions = new FieldList(
				new FormAction('Confirm', 'Purchase')

			return new Form($this, 'Cart', $fields, $actions, $validator);

		 * Validate the form and display order confirmation page
		 * @param $data
		 * @param $form
		 * @return SS_HTTPResponse
		public function Confirm($data, $form) {
			// Error tracking flag
			$error = false;

			// Retrieve the tests
			$tests = TestPage::get();

			// Check if we have any qty for the tests
			$qty = 0;
			foreach ($tests as $test) {
				$key = 'test' . $test->ID;
				if (isset($data[$key]) && strlen($data[$key]) > 0) {
					$qty += (int)$data[$key];
			if ($qty < 1) {
				$form->sessionMessage('You must select at least one test to purchase.', 'bad');
				$error = true;

			if ($error) {
				// Repopulate the form
				Session::set('FormInfo.' . $form->FormName() . '.data', $data);

				// Redirect back
				return $this->redirectBack();

			return $this->redirect('Complete');


Community Member, 187 Posts

3 April 2014 at 4:15am


If I recall correctly, you actually need to set a form error. If you don't want to set an error on a specific field, you can trigger the behaviour anyway by calling this before you redirect back:

Session::set("FormInfo.{$form->FormName()}.errors", array());

The reason is that the data from the session isn't loaded unless an error occurs.



Community Member, 12 Posts

3 April 2014 at 9:02am

Thanks Loz, that works as advertised.