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

后端 未结 6 971
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:26

    I think my first question would be this: if you don't have a model...what are you validating? Typically data collection would be done to populate a model. If you're using an alternative data repository (file, web services, etc.), a model would still be the appropriate way to access and manipulate that data.

    In short, in order to better answer this, I think a little more context would be helpful and maybe even necessary.

    0 讨论(0)
  • 2021-02-13 00:30

    You can perform validation of form data in CakePHP without having to create a model.php file. There are many times when I need to do this, and storing model.php files that do nothing more then validation is a poor usage of the model design pattern.

    Another problem with CakePHP is that sometimes validation rules are common across multiple models. It would be nice to move validation out of the model, much in the way behaviors are to their own subfolder. That way we can re-use them or use them without a model.

    Another problem with validation is that it's dependent upon the model alias. If you have a model called "Email" without a table to perform validation, then the posted form must also use "Email". If the form uses a alias different from the controller, then you have to set the action. A lot of extra steps just to do validation. You can't re-use that model again if your form uses a different model.

    So here is my alternative approach.

    In your controller's action that receives the posted form data. You can create a default CakePHP model, add some validation rules and then use that model for validation.

    An example action might look like this;

    function edit()
    {
       $model = ClassRegistry::init(array('class'=>'Email','table'=>false,'type'=>'Model'));
       if(!empty($this->data))
       {
           $model->validate = array(
               'subject'=>array(
                   'rule'=>'notEmpty',
                   'required'=>true
               ),
               'message'=>array(
                   'rule'=>'notEmpty',
                   'required'=>true
               )
           );
           if($model->save($this->data))
           {
               // validation was successful, but no data was actually saved
           }
       }
    }
    

    The key here is the creation of an automatic model by CakePHP.

           $model = ClassRegistry::init(array('class'=>'Email','table'=>false,'type'=>'Model'));
    

    The above attempts to find a model by Email in the applications model folder. When it is not found CakePHP will auto-create an in memory model for that class. Since we set the value of 'table' to false, then this should tell CakePHP that this model doesn't use a table.

    This works as long as there really isn't a email.php file in the applications model folder. Once this model is created in memory. It's accessible from the built in Form help. That means validation errors will be passed correctly to the view.

    Here is an example view file.

    <?php echo $this->Form->create('Email',array('action'=>array('controller'=>'mycontroller','action'=>'edit'))); ?>
    <?php echo $this->Form->input('subject'); ?>
    <?php echo $this->Form->input('message',array('type'=>'textarea')); ?>
    <?php echo $this->Form->submit(); ?>
    

    The view will now render the validation errors from the Email model using the Form helper. This is because CakePHP class registry has saved a copy of the EMail auto model in memory that the Form helper will access.

    If you want to use custom validation rules, then you will have to put the callback methods in the app_model.php file.

    These methods tested in CakePHP 1.3

    0 讨论(0)
  • 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
           }
       }
    }
    
    0 讨论(0)
  • 2021-02-13 00:35

    Honestly, I'd create a model just for the validation. You can create a model that doesn't use a table by adding

    var $useTable = false;
    

    And then create a validation array with rules for each field you want to validate:

    var $validate = array('login' => 'alphaNumeric','email' => 'email','born' => 'date');
    

    Then, in your controller, do something like:

    $this->MyModel->set($this->data);
    if($this->MyModel->validates()){
        // do stuff with valid data
    }
    

    If you really, really can't use a model, then you'll have to simply loop over each value in $this->data in your controller action and validate it against a regular expression or use the Validation::[rule]() stuff, like:

    if(Validation::email($someThingThatMightBeAnEmailAddress)){
        // do stuff with valid email address.
    }
    
    0 讨论(0)
  • 2021-02-13 00:43

    Came across this question since I also had a similar issue. I have a form that needs to collect data and generate a PDF. So there is no data saving involved nor there is a maching model class. The PDF is a user contract and the user will fill the online form and the data filled will be used to generate the PDF which they must print and mail back. But I need to validate whether the fields are not empty, whether email is really an email format, and date inputs are really date inputs.

    First I did without a model class then saw this quesion. Now I'm using a dummy model class to have my validations put in there since the code in controller action looks much neat.

    0 讨论(0)
  • 2021-02-13 00:45

    Class Validation which is a subclass of Object is used by model class to perform validation against validation rules specified in it.

    One can directly instantiate Validation class inside any controller or model and use its methods for performing validation on any data, not only inputs from forms.

    0 讨论(0)
提交回复
热议问题