Symfony 2 创建动态表单

Symfony 2 Create Dynamic Forms

我想创建一个表单,允许用户从数据库中存储的各种主题中 subscribe/unsubscribe。基本上,所有可用的主题都已存储并需要使用复选框输出,以便用户可以 add/remove 从他们的个人资料中选择该主题。我已经用 vanilla PHP 轻松地做到了这一点,但我是 Symfony2 的新手。这是我到目前为止所拥有的。

我想我已经正确创建了表单,但我不确定如何在此处编写控制器。这只是一个小测试,看看如何做,在这种情况下,保存主题的列称为选项。任何帮助,将不胜感激。提前致谢!

简而言之,我需要将选项列中的所有值列为复选框列表。

FormCheck.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * FormCheck
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class FormCheck
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="options", type="string", length=255)
     */
    private $options;


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set options
     *
     * @param string $options
     * @return FormCheck
     */
    public function setOptions($options)
    {
        $this->options = $options;

        return $this;
    }

    /**
     * Get options
     *
     * @return string 
     */
    public function getOptions()
    {
        return $this->options;
    }
}

FormCheckType.php

<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FormCheckType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('item', 'entity', array(
            'class'    => 'AppBundle:FormCheck',
            'property' => 'options',
            'expanded' => true,
            'multiple' => true,
        ));
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\FormCheck'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_formcheck';
    }
}

FormCheckController.php

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class FormCheckController extends Controller
{
    /**
     * @Route("/form")
     * @Template()
     */
    public function formAction()
    {
        return $this->render('default/formCheck.html.twig');
    }

}

首先,你应该通读the documentation,里面几乎涵盖了你需要的所有内容。

您最好拥有一个用户实体和一个主题实体来存储您的主题并通过多对多关系加入它们。

这样您可以 add/remove 主题和您的表单将更新,并且您不会在每个用户的选项字符串中有重复的信息。

例如(我根本没有检查语法,可能会有拼写错误,但这是我在你的情况下所做的一般要点)

用户

/**
 * @var string
 *
 * @ORM\ManyToMany(targetEntity="YourNamespace\YourBundle\Entity\Topic", mappedBy="users")
 */
protected $topics;

话题

/**
 * @ORM\ManyToMany(targetEntity="YourNamespace\YourBundle\Entity\User", inversedBy="topics")
 * @ORM\JoinTable(name="user_topic",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="topic_id", referencedColumnName="id")}
 *      )
 */
protected $users;

表格

class UserTopicType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('topics', 'entity', array(
            'class'    => 'AppBundle:Topic',
            'property' => 'topics',
            'expanded' => true,
            'multiple' => true,
        ));
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'appbundle_usertopic';
    }
}

控制器

class FormCheckController extends Controller
{
    /**
     * @Route("/form")
     * @Template()
     */
    public function formAction(Request $request)
    {
        $user = // however you get your user here

        $form = $this->createForm(new UserTopicType(), $user);
        $formView = $form->createView();

        $form->handleRequest($request); // request 

        if ($form->isValid()) {

          // persist, flush your user here and redirect to your form
          // or whatever you want to do
        }

        $parameters = array(
            'form' => $formView,
        );

    return $this->render('default/formCheck.html.twig', $parameters);
    }
}