21282 Posts in 5730 Topics by 2601 members
General Questions
SilverStripe Forums » General Questions » validate function not working when adding new dataobject - works for existing ones...
General questions about getting started with SilverStripe that don't fit in any of the categories above.
Moderators: martimiz, Howard, Sean, Ryan M., biapar, Willr, Ingo, swaiba, simon_w
|
Page:
1
|
Go to End | |
| Author | Topic: | 809 Views |
-
validate function not working when adding new dataobject - works for existing ones...

6 January 2011 at 6:28pm Last edited: 6 January 2011 6:28pm
I have the following code:
class MyDO extends DataObject {
........
function validate() {
if($this->MyField) {
return parent::validate();
}
else {
new ValidationResult(false, _t("Order.MUSTSELECTORDER", "You must enter MyField before MyDO can be saved."));
}
}
........
}This code works perfect for saving DataObjects but not for new dataobjects.
How can I fix this?
Nicolaas
-
Re: validate function not working when adding new dataobject - works for existing ones...

11 January 2011 at 5:14am Last edited: 11 January 2011 5:15am
If you use ModelAdmin for your DataObjects, this might be a solution for you:
class MyDO extends DataObject{
:
:
/**
* Validate fields
* @return RequiredFields
*/
public function getCMSValidator(){
$controller = ExtededModelAdmin::curr();
$request = $controller->getRequest();
/* Skip validation when user creates new Translation */
if($request->getVar('action_createtranslation') == 1)
return new RequiredFields();
return new My_Validator();
}
:
:
}
class My_Validator extends RequiredFields{
protected $customRequired = array(your db-array fields to check);
public function __construct() {
$required = func_get_args();
if(isset($required[0]) && is_array($required[0])) {
$required = $required[0];
}
$required = array_merge($required, $this->customRequired);
parent::__construct($required);
}
public function php($data){
/* Check required Fields */
parent::php($data);
/* Special checks */
//Unique & Correct Code
if(!isset($data['Locale'])) $data['Locale'] = Translatable::get_current_locale();
$DOSet = DataObject::get('My_DO', "DO_attr = '$data[DO_attr]' AND Locale = '$data[Locale]'");
if($DOSet instanceof DataObjectSet){
if(($DOSet->Count() > 1) || ($DOSet->First()->ID != $data['ID'])){
$this->validationError('My_DO', 'DO_attr already in use, choose another one.');
}
}
return empty($this->errors);
}
}
| 809 Views | ||
|
Page:
1
|
Go to Top |

