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.

General Questions

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

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

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


Reply

2 Posts   1011 Views

Avatar
Nicolaas

6 January 2011 at 6:28pm (Last edited: 6 January 2011 6:28pm), Forum Moderator, 213 Posts

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

11 January 2011 at 5:14am (Last edited: 11 January 2011 5:15am), Community Member, 88 Posts

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);
   }
}