开发者

cakePHP - form value coudn't validate

My controller:

class PostsController extends AppController 
{
    function index() {
        $this->set('posts', $this->Post->find('all'));
    }
    function add(){
        if(!empty($this->data))
        {
            $this->Post->save($this->data);
            $this->Session->setFlash('the post was saved successfully');
            $this->redirect('/posts/index');
        }
        else
        {
            $this->Session->setFlash('the post was not saved');
        }
    }
}

My model

class Post extends AppModel {
    var $name = 'Post';
    var $validate = array(
        'title'=>array(
            'title_must_not_be_blank'=>array(
                'rule'=>'notEmpty',
                'message'=>'$this post is missing a title'
            ),
            'title_must_be_unique'=>array(
                'rule'=>'isUnique',
                'message'=>'A post with this title already exists'
            )
        ),
        'body'=>array(
            'body_must_not_be_blank'=>array(
                'rule'=>开发者_StackOverflow社区;'notEmpty',
                'message'=>'this post is missing the body'
            )

        )   
    );
}

And my view (I don't use cake html and form helper)

<form action="<?= $this->base.'/posts/add' ?>" method="post">
    <label>title</label>
    <input type="text" name="data[Post][title]" /><br />
    <label>body</label>
    <textarea type="text" name="data[Post][body]"></textarea><br />
    <input type="submit" value="submit" />
</form>

Problem:

when I deliberately left out the fields, the form submitted value to database anyway.

And I'm trying to avoid using html-helpers.


Are you sure the data was saved? Because the controller will redirect you away from the page even if the data doesn't validate.

function add(){
    if(!empty($this->data) ) {
        if( $this->Post->save($this->data) )
        {
            $this->Session->setFlash('the post was saved successfully');
            $this->redirect('/posts/index');
        }
        else
        {
            $this->Session->setFlash('the post was not saved');
        }
    }
}

The next problem is that the validation messages won't show in the view. You need the helpers there to create them, it's a lot of work to do that manually. May I ask why you're not using them?


My answer may be off-topic, but if you're using pure html just because you don't need extra html generated by Form helper (like fieldsets, input wrapped with div, auto-generated label), then you can always use form helper element options e.g.

<label>title</label> <?php echo $this->Form->input('title', array('label'=>false, 'div'=>false, 'legend'=>false) );?>

However I totally agree with @Charles and @Juhana : true power of framework can be unleashed when following it's conventions. So if you want Cake works as advertised - implement as docs advise.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜