How do you perform Form validation without a model in Cakephp?

后端 未结 6 960
Happy的楠姐
Happy的楠姐 2021-02-13 00:06

I need to perform some validation. I don\'t have the model in the application.

Does anyone know how to do the validation without a model? Can you show me using a small s

6条回答
  •  礼貌的吻别
    2021-02-13 00:31

    @ThinkingMedia's answer got me going in the right direction, but $model->save($this->data) was returning false for me unfortunately, even when the form was valid. I'm using CakePHP 2.3.9 for reference.

    It turned out that even with 'table' => false parameter set, the returned$success of save() was based on a $count > 0 of the rows that were created/updated/modified. In my table-less case, this meant a $count of 0 and $success was false. I ended up blending the referenced answer with this similar question's solution to have validation work properly without a model file:

    function edit()
    {
       $model = ClassRegistry::init(array('class'=>'YourFormName','table'=>false,'type'=>'Model'));
       if($this->request-is('post'))
       {
           $model->validate = array(
               'some_field'=>array(
                   'rule'=>'notEmpty',
                   'required'=>true
               ),
               'another_field'=>array(
                   'rule'=>'notEmpty',
                   'required'=>true
               )
           );
           $model->set($this->request->data)
           if($model->validates($this->request->data) && empty($model->validationErrors))
           {
               // validation was successful, but no data was actually saved
           }
       }
    }
    

提交回复
热议问题