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 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)
  • ¥20 关于#stm32#的问题:STM32串口发送问题,偶校验(even),发送5A 41 FB 20.烧录程序后发现串口助手读到的是5A 41 7B A0
  • ¥15 C++map释放不掉
  • ¥15 Mabatis查询数据
  • ¥15 想知道lingo目标函数中求和公式上标是变量情况如何求解
  • ¥15 关于E22-400T22S的LORA模块的通信问题
  • ¥15 求用二阶有源低通滤波将3khz方波转为正弦波的电路