Symfony 表单在多对多实体集合中设置默认复选框值

Symfony form setting default checkbox value in many-to-many entity collection

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

我有一个具有多对多关系的用户实体和选项实体,映射为 b a user_option table。

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

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

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 table 中保存数据,则复选框会正确显示。

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

我要求对于新条目,考虑默认字段。 在构造函数中设置值并没有改变复选框的值,而且无论如何都会将所有字段的默认值设置为true,这不是我想要的。

我正在使用 Symfony 2.6

使用 symfony 2.6

您可以尝试使用 ChoiceType 而不是继承自它的 EntityType

EntityType 只是一种通过选项 class 或更高级的方式,通过指定 class 的实体管理器自动 findAll() 填充选项的方法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 
    ))
;
           

我和 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, 
))

我知道的旧线程。但是这个是 google 中排名最好的,所以我想更新我的解决方案。我认为它非常方便,您不需要那么多代码作为已接受的答案

->add(
        'roles',
        ChoiceType::class,
        [
            'label'   => 'Rolles *',
            'choices' => $this->userService->getRolesForChoiceType(), // change it
            'data'    => [ 1, 3 ] // change it to your default choices
            'help'    => 'some help text'
        ]
    )

此代码来自 Symfony 4.4

希望安全的人多一些google查询