今天进入了狗屎皮重构的第三天。今天要解决一个很关键的问题:如何让用户贴出评论?
先看界面:
这时一个标准的主从表界面:帖子内容、已经有了的评论内容再加上一个表单方便用户提交评论。
我本来认为要完成用户提交评论,在Symfony下是很简单的——简单到你可以不用写任何额外的代码,但实际情况并不如此。
主要的一些修改如下。
首先,要修改article的action.class.php文件中的executeShow函数:
class articleActions extends sfActions
{
public function executeShow(sfWebRequest $request)
{
$article=$this->getRoute()->getObject();
$this->article = $article;
$this->comments=Doctrine_Core::getTable('g4pcomment')->getComments($article->getId());
$this->form=new G4pCommentForm();
}
......
}
上述代码中必须人肉创建了一个comment的表单,并传递到模板中进行进一步处理。
在showSuccess.php模板中,通过include_partial来显示comment表单:
include_partial('comment/form', array('form'=>$form, 'article_id'=>$article->getId()));
注意,我还额外传递了一个article_id参数进去,这是为了后续的处理。
修改comment表单文件如下,让它带一个article_id的参数:
<?php echo form_tag_for($form, '@comment') ?>
最后,修改comment的create以及processForm函数:
public function executeCreate(sfWebRequest $request)
{
$this->forward404Unless($request->isMethod(sfRequest::POST));
$aid=$request->getParameter('aid');
$nc=new G4pComment();
$nc->set('article_id', $aid);
$nc->set('created_at', date('Y-m-d H:i:s'));
$this->form = new G4pCommentForm($nc);
$this->processForm($request, $this->form);
//$this->setTemplate('article/show');
}
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
if ($form->isValid())
{
$comment = $form->save();
$article=$comment->getG4pArticle();
//var_dump($article);
$this->redirect($this->generateUrl('show_article', array('id'=>$article->getId(), 'title_slug'=>$article->getTitleSlug())));
}
}
在executeCreate函数中,设置了一个comment的外键article_id(从前一个页面传递过来),设置了comment创建的时间。
在processForm函数中,需要修改一下处理完毕后的重定向,回到原来的帖子的页面,显示帖子、评论等。
最后,我不得不说两句。我认为这个要求是几乎所有WEB程序都会用到的,但是我提问到Symfony的官方论坛后三天没有人回答!最后还是靠自己解决了问题……
(本文收录于[go4pro.org])
Leave a Reply