douyi6290 2013-09-27 04:10
浏览 45
已采纳

使用自定义表单/没有formhelper的Cakephp验证

Can I use Cakephp validation without formhelper?

for example, I was created model, controller, and view like this

model:

class KnowledgeBase extends AppModel {
   public $useTable = 'corp_kb';

 public $validate = array(
        'kb_title' => array(
            'rule' => array('minLength', '2'), 
            'required' => true,
            'message' => 'min 2 char'
        ),
);
}

controller:

class KnowledgeBaseController extends AppController 
{
var $name = 'KnowledgeBase';
var $ext = '.php';
public $helpers = array ('Html', 'Form', 'Js');

function kb_fill()
    {
    $this->layout = 'ajax';
    }

function kb_input()
    {
    $this->autoRender = false;
    $this->KnowledgeBase->set($this->data);
    if(!empty($this->data))
    {
        if($this->KnowledgeBase->validates())
        {
        debug($this->data);
        }
        else
        {

        }
    }
    else 
    {
    echo "data empty";
    }
    }

view "kb_fill":

<form id="kb_frm" method="get" action="" >
<input type="text" name="data[Knowledgebase][kb_title]"/>
<button id="postbutton">Post !</button>
</form>

for some reason I used ajax to load post into kb_input via button id, and cannot use usual method. the cakephp validation not working, or not showing the message error how can I use it without formhelper?

  • 写回答

2条回答 默认 最新

  • dplbf4340 2013-09-27 04:18
    关注

    You are halfway there. The method $this->KnowledgeBase->validates() in your Controller will only return true or false. To manually work on the validation errors, you'll need this:

    if ($this->KnowledgeBase->validates()) {
        // it validated logic
    } else {
        // didn't validate logic
        $errors = $this->KnowledgeBase->validationErrors;
    }
    

    Took the code sample from Validating Data from the Controller, I would recommend you to take a look at it, as you may find further information about how to validate your data via Controller.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算