dongtingxiao4697 2016-02-28 14:53
浏览 28
已采纳

CakePHP 2中的表单验证

In my view I have

<?= $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); 
?>

In my Controller, I have

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

        }

In my Model, I have

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

When I submit the form, logically it should not get submitted and print out the error message but the form gets submitted instead and validates the model inside controller which breaks the operation in controller.

  • 写回答

1条回答 默认 最新

  • doupeng6890 2016-02-29 11:43
    关注

    You have to check validation in your controller like

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

    You will have your ID there in variable $semisid, or you can set data in $this->request->data = $this->Asc201516->findById($semisid);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?