是否可以使用CollectionType将表单类型的标签值设置为数据对象中可用的属性值?
主窗体类型类:
class ShapeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('shape_fractions', CollectionType::class, [
'entry_type' => ShapeFractionType::class,
'entry_options' => ['label' => false],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Shape::class,
]);
}
}
Shape数据类:
class Shape
{
public array $shape_fractions;
// ...
}
形状分数类型:
class ShapeFractionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// 'data' index not available in collection mode:
$shapeFraction = $options['data'];
$builder
->add('value', NumberType::class, [
'label' => $shapeFraction->name //error
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => ShapeFraction::class,
]);
}
}
ShapeFraction数据类:
class ShapeFraction
{
public string $name;
public string $type;
public float $value;
// ...
}
呈现窗体:
$shapeFractions = [
new ShapeFraction('A', 'length', 10),
new ShapeFraction('B', 'length', 20),
]
$shape = new Shape($shapeFractions)
$form = $formFactory->create(ShapeType::class, $shape);
// Render using Twig...
结果是一条错误消息,指出“data”索引在选项中不可用。直接使用ShapeFractionType而不使用ShapeType的父层,可以正常工作。因此,似乎CollectionType出于某种原因去除了“data”索引。
我的主要目标是使用分数的“name”属性作为值字段的标签:形状:答:<input..>B:<input..>
先谢了!
1条答案
按热度按时间km0tfn4u1#
您可以使用事件侦听器来访问集合中的“当前”项,这应该有效:
此答案的出处:https://stackoverflow.com/a/55352083/3960296