【问题标题】:Symfony form setting default checkbox value in many-to-many entity collectionSymfony表单在多对多实体集合中设置默认复选框值
【发布时间】:2016-02-04 16:04:00
【问题描述】:

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

我有一个具有多对多关系的用户实体和选项实体,映射到一个 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 版本?
  • 2.6 - 我更新了我的问题。谢谢。

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


【解决方案1】:

使用 symfony 2.6

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

在您的情况下,首先创建一个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+

(待公关见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 
    ))
;
           

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      希望更多的谷歌查询能保护某人

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-05
        • 2012-01-19
        • 1970-01-01
        • 2016-10-01
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        相关资源
        最近更新 更多