【发布时间】:2018-06-07 12:04:06
【问题描述】:
我对 Symfony 3.4 EntityType 有疑问。
CategoryType.php
class CategoryType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('spec', CollectionType::class, [
'entry_type' => SpecificationType::class,
'allow_add' => true,
'allow_delete' => true,
'label' => false,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Category::class,
));
}
}
SpecificationType.php
class SpecificationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', EntityType::class, [
'class' => Specification::class,
'label' => false,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Specification::class,
));
}
public function getBlockPrefix()
{
return 'specification';
}
}
表单按预期呈现:标题为文本字段,以及 2 个选择元素。但问题是呈现选择元素没有选择选定的值。
form.html.twig
{{ form_widget(form.title) }}
{{ form_widget(form.spec) }}
当 SpecificationType.php EntityType::class 被 TextField:class 替换时,现在表单呈现不是 2 个选择元素总线 2 个文本输入(预期行为)并且分配的值是正确的:
我开始挖掘这些选择元素是如何渲染的,发现这个块{%- block choice_widget_options -%}负责渲染选择元素。
这个块里面是和平的代码:
<option value="{{ choice.value }}"{% if choice.attr %}{% with { attr: choice.attr } %}{{ block('attributes') }}{% endwith %}{% endif %}{% if choice is selectedchoice(value) %} selected="selected"{% endif %}>{{ choice_translation_domain is same as(false) ? choice.label : choice.label|trans({}, choice_translation_domain) }}</option>
正是这个条件:{% if choice is selectedchoice(value) %} selected="selected"{% endif %} 负责将selected 属性添加到选项。但selectedchoice(value) 扩展中的value 不知何故为空,这就是他没有将选项标记为选中的原因。
也许有人知道,如何解决这个问题?
更新
spec 属性定义如下:
CategoryEntity.php
/**
* @ORM\ManyToMany(targetEntity="Specification", inversedBy="categoryList")
* @ORM\JoinTable(name="category_specification")
*/
private $spec;
【问题讨论】:
-
您能否说明
spec属性是如何在Category实体中定义的? -
@Djengobarm 请参阅更新部分。
标签: php symfony twig symfony-3.4