我有以下情况。 帖子的hasMany评论CakePHP 2.1:以平稳的方式验证元素的表单?
评论通过belongsTo帖子
在我/浏览/职位/视图,我展示了邮政与它的评论。另外,每个帖子都应该显示评论表单。因此,我必须使用元素add_comment.ctp来查看(请纠正我,如果我错了,但请参阅this question here)。
/Views/Posts/view.ctp:
// add comments
echo $this -> element('add_comment',array('post_id' => $entry['Post']['id']), array('cache' => array('config' => 'long')));
元素:
/**
* Element for adding comments
*
*/
echo $this -> Form -> create('Comment', array('url' => array(
'controller' => 'comments',
'action' => 'add',
$post_id
)));
?>
<fieldset>
<legend><?php echo 'Add Comment'; ?></legend>
<?php
echo $this -> Form -> input('author_name');
echo $this -> Form -> input('author_email', array('type' => 'email required'));
echo $this -> Form -> input('author_website');
//echo $this->Form->input('date_published');
echo $this -> Form -> input('text');
//echo $this->Form->input('is_archived');
?>
</fieldset>
<?php echo $this -> Form -> end(array('label' => 'Post!')); ?>
正如你可以看到,表单被提交到CommentsController的附加动作。 现在,一个大问题:添加动作如何将验证结果等数据实际传递回表单?我的意思是,表格数据也应该被保留下来,所以如果有人输入无效数据,它不会丢失。
通常情况下,添加动作会渲染/查看/评论/添加,但我不需要这个视图,我甚至没有定义一个。
到目前为止,我已经使用$ this-> redirect在评论保存之后返回到/ Views/Posts/view - 但只是调用/ Views/Posts/view而不传递任何东西。那么,如何才能使用Elements与Smooth和Automagic表单处理结合使用呢?
感谢您的回答!为了澄清,通过编号1,您的意思是,评论/ add.ctp将在验证后呈现,而不显示帖子?即,仅用于添加评论的新视图?如果是的话,这不是最佳的解决方案,但考虑到2号显然打破了MVC模式,可能是最容易实现的,对吗? – wnstnsmth 2012-07-06 10:10:04
是的,您可以在第一个地方显示添加评论表单,但在同一个地方处理数据。 #2不一定会破坏MVC模式,只是你会在后控制器中添加一些注释逻辑,看起来有点奇怪 – Dunhamzzz 2012-07-06 10:24:25
你是否设法以可接受的方式解决这个问题?我有同样的问题。 – Cos 2012-09-23 14:07:13