Symfony 2将变量传递给表单类,以在表单中动态创建隐藏字段

时间:2011-09-30 01:06:32

标签: forms symfony

我正在研究一种关于symfony 2框架的博客工具,其中帖子可以有很多评论。我在各个实体的帖子和评论之间建立了一对多的关系。当帖子显示在主页上时,我想在其下面有一个评论表单,用户可以在其中发表评论。为了发表评论,我必须在postID的表单中传递一个隐藏字段,但我无法这样做。以下是我的所有代码..

控制器:

<?php

namespace Issh\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Issh\MainBundle\Form\Post\CommentForm;
use Issh\MainBundle\Form\Post\PostForm;
use Issh\MainBundle\Entity\IsshPost;
use Issh\MainBundle\Entity\IsshComment;

class HomeController extends Controller
{

    public function indexAction()
    {
        return $this->render('IsshMainBundle:Home:index.html.php');
    }

    public function postAction()
    {
        $em = $this->get('doctrine')->getEntityManager();
        $request = $this->get('request');

        $post = new IsshPost();        
        $form = $this->createForm(new PostForm(), $post);

        if ('POST' == $request->getMethod()) 
        {        
            $form->bindRequest($request);           
            $post->setIsshUser($this->get('security.context')->getToken()->getUser());

            if ($form->isValid()) 
            {
                $em->persist($post);
                $em->flush();

                return $this->redirect($this->generateUrl('home'));
            }
            return $this->render('IsshMainBundle:Home:IsshPost.html.php', array(
                 'form'  =>  $form->createView()));   
        }
        else
        {
            $em = $this->getDoctrine()->getEntityManager();
            $posts = $em->getRepository('IsshMainBundle:IsshPost')->getLatestPosts();
            return $this->render('IsshMainBundle:Home:IsshPost.html.php', array(
                'form'  =>  $form->createView(), 'posts' => $posts));           
        }

    }

    public function commentAction($postID = null)
    {
        $em = $this->get('doctrine')->getEntityManager();
        $request = $this->get('request');

        $comment = new IsshComment();        
        $form = $this->createForm(new CommentForm($postID), $comment); // need to pass postID here so it can be set as hidden field

        if ('POST' == $request->getMethod()) 
        {        
            $form->bindRequest($request);           
            $comment->setIsshUser($this->get('security.context')->getToken()->getUser());  

            if ($form->isValid()) {
                $em->persist($comment);
                $em->flush();

                return $this->redirect($this->generateUrl('home'));
            }

        }
        else
        {
            return $this->render('IsshMainBundle:Home:IsshComment.html.php', array(
                'form'  =>  $form->createView()));
        }     
    }
}

这是帖子表格:

<?php

namespace Issh\MainBundle\Form\Post;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class PostForm extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('text','text');
    }

    public function getName()
    {
        return 'postForm';
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Issh\MainBundle\Entity\IsshPost'
        );
    }
}
?>

评论表格(暂不行):

<?php

namespace Issh\MainBundle\Form\Post;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class CommentForm extends AbstractType
{

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('text','text');
    }

    public function getName()
    {
        return 'commentForm';
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'Issh\MainBundle\Entity\IsshComment'
        );
    }
}
?>

帖子模板:

<?php if(!empty($form)): ?>
<form action="<?php echo $view['router']->generate('post') ?>" method="post" <?php echo $view['form']->enctype($form) ?> >
    <?php echo $view['form']->errors($form) ?>
    <?php echo $view['form']->row($form['text']) ?>
    <?php echo $view['form']->rest($form) ?>
    <input type="submit" />
</form>
<?php endif; ?>
<?php if(!empty($posts)): ?>
    <?php foreach ($posts as $post): ?>
    <p><?php echo $post->getText();?></p>
    <?php 
    //embed comment controller in view
    echo $view['actions']->render('IsshMainBundle:Home:comment',array('postID' => $post->getId())); 
    ?>
    --------------------------------------
    <?php endforeach; ?>
<?php endif; ?>

评论模板:

<?php if(!empty($form)): ?>
<form action="<?php echo $view['router']->generate('comment') ?>" method="post" <?php echo $view['form']->enctype($form) ?> >
    <?php echo $view['form']->errors($form) ?>
    <?php echo $view['form']->row($form['text']) ?>
    <?php echo $view['form']->rest($form) ?>
    <input type="submit" />
</form>
<?php endif; ?>
<?php if(!empty($comments)): ?>
    <?php foreach ($comments as $comment): ?>
    <p><?php echo $comment->getText();?></p>
    --------------------------------------
    <?php endforeach; ?>
<?php endif; ?>

2 个答案:

答案 0 :(得分:5)

您可以在表单类中声明构造函数,并将postID传递给表单。

class CommentForm extends AbstractType
{
    private $postId;

    public function __construct($postId = null)
    {
        $this->postId = $postId;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
    ... 
}

您现在可以在表单中的任何位置以$ this-&gt; postId的形式访问postID。

答案 1 :(得分:3)

你可以简单地为buildForm方法添加一个选项:

  

$ form = $ this-&gt; get('form.factory') - &gt; create(new FormType(),array('key'=&gt;'var'));