1

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!

1 Answer 1

1

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
]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this solves the issue. My real case only was more complex. The fractions are part of a shape object. I use the CollectionType to render the fractions. In that case, the data index is not available within the $options array. I created a new question for this case: stackoverflow.com/questions/75020710/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.