CakePHP 2中的表单验证

时间:2016-02-28 14:53:44

标签: php forms validation cakephp cakephp-2.0

在我看来,我有

<?= $this->Form->create('Asc201516', array(
'url' => array(
    'controller' => 'asc201516s', 
    'action'     => 'submit_asc201516'
    ), 
'class' => 'form-inline',
'onsubmit' => 'return check_minteacher()'
)); ?>

<div class="form-group col-md-3">
    <?= $this->Form->input('bi_school_na', array(
        'type' => 'text',
        'onkeypress' => 'return isNumberKey(event)',
        'label'       => 'NA', 
        'placeholder' => 'NA', 
        'class'       => 'form-control'
    )); ?>
</div>
<?php 
$options = array(
    'label' => 'Submit',
    'class' => 'btn btn-primary');
echo $this->Form->end($options); 
?>

在我的控制器中,我有

$this->Asc201516->set($this->request->data['Asc201516']);
        if ($this->Asc201516->validates()) {
            echo 'it validated logic';
            exit();

        } else {                
            $this->redirect(
                array(
                    'controller' => 'asc201516s',
                    'action' => 'add', $semisid
                    )
                );

        }

在我的模型中,我有

 public $validate = array(
        'bi_school_na' => array(
            'Numeric' => array(
                'rule' => 'Numeric',
                'required' => true,
                'message' => 'numbers only',
                'allowEmpty' => false
            )
        )
    );

当我提交表单时,逻辑上它不应该被提交并打印出错误消息但是表单被提交而是验证控制器内的模型,它打破了控制器中的操作。

1 个答案:

答案 0 :(得分:1)

您必须在控制器中检查验证,如

$this->Asc201516->set($this->request->data);  
if($this->Asc201516->validates()){  
    $this->Asc201516->save($this->request->data);  
}else{  
    $this->set("semisid",$semisid);
    $this->render("Asc201516s/add");
}

您的ID位于变量$semisid,或者您可以在$this->request->data = $this->Asc201516->findById($semisid);

中设置数据