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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Custom validation for CMS admin which compares values across multiple fields.


Go to End


2 Posts   733 Views

Avatar
jcop007

Community Member, 7 Posts

1 December 2015 at 3:33pm

Hi
I need to check that the departure date is after the arrival date in a CMS model admin form. I've found out how to make the fields required and I see you can create custom fields to add custom validation for each field but not sure where or how to add validation that works across multiple fields?
At the moment my only validation is required fields on the DataObject:
e.g
class Tour extends DataObject{
private static $singular_name = "Tour";
private static $plural_name = "Tours";

private static $db = array(
'Departure' => 'Time',
'Arrival' => 'Time'
);

function getCMSValidator() {
return new RequiredFields(array('Departure', 'Arrival'));
}

Thanks

Avatar
Devlin

Community Member, 344 Posts

2 December 2015 at 2:49am

You'll need to overload RequiredFields and add your custom validation to the existing validation. Something like:

new DepartureArrivalValidator(array('Departure', 'Arrival'));

class DepartureArrivalValidator extends RequiredFields {
	public function php($data) {
		$valid = parent::php($data);

		if ($data['Departure'] === $data['Arrival']) {
			$this->validationError(
				'Departure', 'Departure not valid.', 'required'
			);
			$this->validationError(
				'Arrival', 'Arrival not valid.', 'required'
			);
			$valid = false;
		}

		return $valid;
	}
}