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

3

我遇到了一个问题,无法为多对多关系显示的复选框设置默认值。

我有一个用户实体和一个选项实体,它们之间是多对多的关系,由一个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


你好,你使用的Symfony版本是哪个? - Heah
2.6 - 我更新了我的问题。谢谢。 - crafter
3个回答

2

使用Symfony 2.6

您可以尝试使用ChoiceType代替继承自它的EntityType

EntityType只是一种通过选项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请查看链接)

// 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

我使用 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, 
))

0

虽然这是一个旧帖子,但它在谷歌排名最高,所以我想更新我的解决方案。我认为这非常方便,而且你不需要像被接受的答案那样写太多代码。

->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。
希望能帮助某些人减少谷歌搜索次数。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接