Home > OS >  Symfony Forms, formtype label based on a property value of the data object
Symfony Forms, formtype label based on a property value of the data object

Time:01-05

Is it possible to set the label value of a form type to be a property value that is available in the data object?

My FormType class:

class ShapeFractionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('value', NumberType::class, [
                'label' => 'name'
            ]);
    }

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

The ShapeFraction data class:

class ShapeFraction
{
    public string $name;
    public string $type;
    public float $value;

    // ...
}

Rendering the form:

$shapeFraction = new ShapeFraction('A', 'length', 10);
$form = $formFactory->create(ShapeFractionType::class, $shapeFraction);

// Render using Twig...

The result is a simple form containing a single input with 'name' as label. Is it possible to use the property value of ShapeFraction::$name as the label of the field? Result will become like this: A: <input..>. I would like to achieve this without using the object data directly in Twig or something.

Thanks in advance!

CodePudding user response:

You can access the data that you pass to your form using $options['data'].

That means you can do this:

/** @var ShapeFraction $shapeFraction */
$shapeFraction= $options['data'];
$builder->add('value', NumberType::class, [
    'label' => $shapeFraction->name
]);
  • Related