如何使用模型和控制器验证cakephp中的表单字段

时间:2014-10-10 08:54:44

标签: php cakephp cakephp-2.3

我创建了一个表单,我需要使用模型和控制器进行验证。这是我的表单

index.ctp

    <?php echo $this->Form->create('Contact',array('url'=>array('controller'=>'contacts','action'=>'add'))); 

 echo $this->Form->text('name');

型号:Contact.php

class Contact extends AppModel
{
        var $name = 'Contact';
        var $useTable = false;

       public $validate = array(
        'name' => array(
            'alphaNumeric' => array(
                'rule'     => 'alphaNumeric',
                'required' => false,
                'message'  => 'Letters and numbers only'
            ),
            'between' => array(
                'rule'    => array('between', 5, 15),
                'message' => 'Between 5 to 15 characters'
            )
        )
    );
} 

Controller:ContactsController.php

public function add()
    {
         $this->Contact->validates();

            $this->request->data['Country']['country_name']=$this->request->data['Contact']['country'];

            $this->Country->saveall($this->request->data);

            $this->redirect('/Contacts/index/');

    }

我正在尝试通过谷歌搜索进行验证,但对我来说似乎很难,所以如果有人能描述这个过程,那将是一个很大的帮助。我的cakephp版本是2.3.8。我只需要验证此名称字段,因为当我单击提交时,它将在表单中显示此消息。

1 个答案:

答案 0 :(得分:1)

你的控制器代码应该是这样的 CakePHP中的验证过程就像

1) as you have defined validation rules in CakePHP model public `$validates = array();`

2) when ever you do a save on particular model directly or through any association 
a callback method beforeValidate for that model gets called to validate the data which is being saved. 

3) once the data is validated then beforeSave callback is called after this save method is called. 

4) we can also validate the form input fields in controller using $this->Model->validates() but then while saving we have to disable the beforeValidate callback by doing 

$this->Model->save($data,array('validate'=>false));

否则您将结束两次验证相同的数据

您的控制器代码应该有点像这样。

public function add() {
        // here we are checking that the request is post method
        if ($this->request->is('post')) {
               $this->request->data['Country']['country_name']
                               = $this->request->data['Contact']['country'];
                // here we are saving data
            if ($this->Contact->saveAll($this->request->data)) {

                //here we are setting a flash message for user
                $this->Session->setFlash('your record has been added','success');

                $this->redirect(array('controller'=>'contacts','action' => 'index'));
            } else {
                //here we are setting a flash message for user for error if input are not          
                //validated as expected
                $this->Session->setFlash('sorry we could add your record','error');
            }

        }

    }

有关详情,请随时参阅http://book.cakephp.org/2.0/en/models/callback-methods.html