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

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

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献