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're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

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

validate function not working when adding new dataobject - works for existing ones...


Go to End


2 Posts   1389 Views

Avatar
Nicolaas

Forum Moderator, 224 Posts

6 January 2011 at 6:28pm

Edited: 06/01/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

Avatar
dompie

Community Member, 88 Posts

11 January 2011 at 5:14am

Edited: 11/01/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);
	}
}