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.

    点赞 打赏 评论
  • dongpo0409 2013-09-27 08:36

    Inorder to show error messages we need to put this error method of form helper. i.e.

    <?php echo $this->Form->error('kb_title') ?>
    

    If you use cakephp Formhelper input method then it will give error messages by default, where as if you use any static html like yours then you've to use error method of form helper to display error messages.

    <form id="kb_frm" method="get" action="" >
    <input type="text" name="data[Knowledgebase][kb_title]"/>
    <?php echo $this->Form->error('kb_title') ?>
    <button id="postbutton">Post !</button>
    </form>
    

    you can get the validation error of a form using error method of form helper, if you don't want to use this method then you can have a look at on $validationErrors Property of view here

    so you can get the error message by using $this->validationErrors['Knowledgebase']['kb_title']

    点赞 打赏 评论

相关推荐 更多相似问题