Symfony表单设置多对多实体集

时间:2016-02-04 16:04:00

标签: forms symfony checkbox many-to-many entity

我在为多个关系显示的复选框设置默认值时遇到问题。

我有一个具有多对多关系的User实体和Options实体,映射到user_option表。

在用户表单中,我会在复选框中显示选项列表。

选项实体包含一个默认字段,指示是否为新用户设置或取消设置复选框。如果用户已选择,则必须显示用户选择。

class User {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(name="name", type="string", length=64, nullable=true)
     */
    protected $name;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Bundle\Entity\Option", inversedBy="users")
     * @ORM\JoinTable(name="user_options")
     */
    protected $userOptions;
}

class CommunicationOption {

   /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=50)
     */
    protected $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="default_state", type="boolean")
     */

}

表单加载选项

public function buildForm(FormBuilderInterface $builderInterface, array $options)
{
    $builderInterface
        ->add('userOptions', 'entity', array(
            'class' => 'Bundle\Entity\Option',
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            'query_builder' => function (EntityRepository $repository) {
                return $repository->getFindAllQueryBuilder();
            },
            'by_reference' => true,
        ))
    ;
}

显示所有选项。但是,未选中所有复选框。 如果用户将数据保存在user_options表中,则会正确显示该复选框。

    {% for element in form.userOptions %}
       {{ form_widget(element, {'attr': {'class': 'col-xs-1' }}) }}
       {{ element.vars.label|raw }}
    {% endfor %}

我要求对新条目使用默认字段。 在构造函数中设置值不会更改复选框值,并且在任何情况下都会将所有字段的默认值设置为true,这不是我想要的。

我正在使用Symfony 2.6

3 个答案:

答案 0 :(得分:2)

使用symfony 2.6

您可以尝试使用ChoiceType代替继承自EntityType的{​​{1}}。

EntityType只是一种通过选项findAll()或更高级的class选项,使用自动query_builder形式指定类的实体管理器来填充选项的方法

在您的情况下,首先创建一个Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class SomeController extends Controller
{
    public function someAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $options = em->getRepository('\AppBundle\Entity\CommunicationOption')
            ->findAll();

        // from here we are making a custom choice loader
        $choices = array(); // will hold the indexed labels the user will choose
        $mappedUserOptions = array(); // will hold each $option as $label => $option

        // we want each $choice as $index => $label, where $value is the index in $choices
        foreach($options $as $option) {
            $choices[] = $option->getName(); // 0 => 'Some Option Name'
            $mappedOptions[$option->getName()] = $option; // 'Some Option Name' => CommunicationOption $option
        }

        // now I skip the part when you create a form builder for the user then :
        $builder = // ... create your user form
        $form = $builder->add('userOptions', 'choice', array(
            'choice_list' => new ChoiceList(
                array_fill(0, count($choices), true), // the checkbox input value will be normalised to string "on", false would be normalised to false
                $choices, // labels for the user to choose
            ),
            'expanded' => true,
            'multiple' => true,
            'required' => false,
            'by_reference' => true, // not needed, it is the default
        ))
        ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // get an array of selected labels
            $userOptions = $form->get('userOptions')->getData(); // array('Some User Option', 'Some Other Option')
            // remap the options to to data
            $selectedUserOptions = array(); // CommunicationOption[]
            foreach ($userOptions as $choice) {
                $selectedUserOptions[] = $mappedOptions[$choice];
            }
            $user = $form->get('user')->getData();

            $user->setOptions($selectedUserOptions);

            // ... persists and flush
            // you could redirect somewhere else
        }

        // return a response
    }
}

但是我建议升级到symfony 2.7甚至更好2.8。

使用symfony 2.7 +

(等待PR见link

// Just copy-pasted your example before edit :
$builderInterface
    ->add('userOptions', 'entity', array(
        'class' => 'Bundle\Entity\Option',
        'expanded' => true,
        'multiple' => true,
        'required' => false,
        'query_builder' => null, // omit it will load all entity by default
        'by_reference' => true, // not needed
        // Using new option introduced in 2.7 see the [doc](http://symfony.com/doc/2.7/reference/forms/types/choice.html#choice-value)
        'choice_value' => 'on', // this only should make the trick 
    ))
;

答案 1 :(得分:2)

我知道的旧线程。但这是Google排名最高的,所以我想更新我的解决方案。我认为这非常方便,您不需要那么多的代码即可接受答案

The image “http://localhost:3000/” cannot be displayed because it contains errors.

此代码来自Symfony 4.4

希望其他人可以安全地进行一些Google查询

答案 2 :(得分:1)

我与symfony3合作。这是它的工作原理

->add('aptitudes', EntityType::class, array( //change this line
      'class' => 'BackendBundle:Aptitudes', //change this line
      'expanded' => true,
      'multiple' => true,
      'required' => false,
      'query_builder' => null, 
      'by_reference' => true, 
))