gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:10:12 26 4
gpt4 key购买 nike

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

我有一个具有多对多关系的用户实体和选项实体,映射到 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

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

EntityType 只是一种通过选项 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
))
;

关于forms - Symfony 表单在多对多实体集合中设置默认复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com