Created
March 31, 2014 13:21
-
-
Save mattclegg/9892105 to your computer and use it in GitHub Desktop.
MyAwesomePage Validation for has_many fields (in the CMS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyAwesomePage extends Page { | |
static $has_many = array( | |
"Things" => "AwesomeDataObjects" | |
); | |
public function getCMSFields() { | |
$fields = parent::getCMSFields(); | |
$fields->addFieldToTab("Root.Content.Stuff", new ComplexTableField( | |
$this, | |
"Things", | |
"AwesomeDataObjects" | |
)); | |
return $fields | |
} | |
function getCMSValidator(){ | |
return new MyAwesomePage_Validator("Things"); | |
} | |
} | |
class MyAwesomePage_Validator extends RequiredFields { | |
protected $required_many; | |
function validate(){ | |
$x = parent::validate(); | |
if($this->getErrors()){ | |
if(Director::is_ajax() && $this->getJavascriptValidationHandler() == 'prototype') { | |
foreach($this->getErrors() as $Error){ | |
FormResponse::status_message($Error["message"],'bad'); | |
} | |
} | |
} | |
return false; | |
} | |
function php($data) { | |
$obj = $this->form->getRecord(); | |
$hasMany = Object::combined_static($obj->ClassName, 'has_many', 'DataObject'); | |
foreach($this->required as $field) { | |
if($hasMany && array_key_exists($field, $hasMany)) { | |
$this->removeRequiredField($field); | |
$this->required_many[] = $field; | |
} | |
} | |
$valid = parent::php($data); | |
if($this->required_many) { | |
foreach($this->required_many as $fieldName) { | |
if($obj->$fieldName()->Count() == 0) { | |
$formField = $this->form->Fields()->dataFieldByName($fieldName); | |
$this->validationError( | |
$fieldName, | |
$formField->getCustomValidationMessage() ? | |
$formField->getCustomValidationMessage() : | |
sprintf(_t('Form.FIELDISREQUIRED', '%s is required').'.', strip_tags('"' . ($formField->Title() ? $formField->Title() : $fieldName) . '"')), | |
"required" | |
); | |
$valid = false; | |
} | |
} | |
} | |
return $valid; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check required fields for Pages in SS2 with "has_many" fields.
This is in response to;
http://www.silverstripe.org/customising-the-cms/show/13397
http://www.silverstripe.org/data-model-questions/show/6128#post287065