php Symfony Forms -CollectionType中数据对象属性的字段类型标签

a1o7rhls  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(117)

是否可以使用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..>
先谢了!

km0tfn4u

km0tfn4u1#

您可以使用事件侦听器来访问集合中的“当前”项,这应该有效:

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

class ShapeFractionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $form = $event->getForm();
            $form->add('value', NumberType::class, [
                'label' => $event->getData()->name
            ]);
        });
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => ShapeFraction::class,
        ]);
    }
}

此答案的出处:https://stackoverflow.com/a/55352083/3960296

相关问题