CakePHP-3.0插件表单验证错误消息和输入的数据

时间:2015-02-19 11:07:14

标签: cakephp plugins cakephp-3.0

我创建了一个CommentManager插件,用于在我的帖子中添加评论。在Posts/view.ctp文件和评论表单操作中添加评论表单会重定向到CommentManager/Comments/add

评论正确保存,但在保存空表单时,没有显示我在CommentsTable中写入的验证错误消息,并且输入的数据也已从表单中删除。

CommentManager / SRC /控制器/ CommentsController /添加

public function add()
{
    $ccomment = $this->Comments->newEntity($this->request->data);
    if ($this->request->is('post')) {
        $newData = ['post_id' => $this->request->params['pass'][0]];
        $ccomment = $this->Comments->patchEntity($ccomment, $newData);

        if ($this->Comments->save($ccomment)) {
            $this->Flash->success('The comment has been saved.');
            return $this->redirect($_SERVER['HTTP_REFERER']);
        } else {
            $this->Flash->error('The comment could not be saved. Please, try again.');
        }
    }
    $this->set(compact('ccomment'));        
    return $this->redirect($_SERVER['HTTP_REFERER']);
}

CommentManager / SRC /型号/表/ CommentsTable

public function validationDefault(Validator $validator) {
    return $validator
        ->notEmpty('body', 'Body contents required.')
        ->notEmpty('email', 'An email is required.')
        ->add('email', [
            'format' => [
                'rule' => [
                    'custom',
                    '/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
                ],
                'message' => 'Enter a valid email.'
            ]
        ]);
}

的src /模板/帖子/ view.ctp

<?php echo $this->Html->link('Back', ['action' => 'index']) ?>
<?php echo $this->element('check_login'); ?>
<br/>
<?php $img_path = DS.'webroot'.DS.'images'.DS.$post->image; ?>
<img src="<?php echo empty($post->image)?'':$img_path; ?>">
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->body; ?></p>
<p><small><?php echo $post->created->format('d M Y'); ?></small></p>


<h3>Comments:</h3>
<?php foreach ($comments as $comment) { ?>
    <p><?php echo $comment->body; ?></p>        
<?php } ?>

<?php
echo $this->Form->create(null, ['url' => ['plugin' => 'CommentManager', 'controller' => 'Comments', 'action' => 'add', $post->id]]);
echo $this->Form->input('body', ['type' => 'textarea', 'rows' => '5', 'cols' => '5']);
echo $this->Form->input('email');
echo $this->Form->button('Save');
echo $this->Form->end();
?>

1 个答案:

答案 0 :(得分:0)

请勿使用空数组调用newEntity()。而不是

$ccomment = $this->Comments->newEntity($this->request->data);

执行:

$ccomment = $this->Comments->newEntity();

在致patchEntity()的电话中传递$this->request->data