Search code examples
symfonysymfony-forms

Possible to provide custom names for mapped entity fields/properties in a Symfony form?


I am working with Symfony 3.4. Assume there is an entity Task with some properties, e.g. title, note, etc.

When creating a custom FormType to let the user create a new Task entity, each entity property is usually added using its internal name:

class TaskType extends AbstractMoneyControlBaseType { 
    public function getBlockPrefix() {
        return 'app_task';
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
            ->add('title', TextType::class, [
                'label' => 'The Title'
            ])        
            ->add('note', TextType::class, [
                'label' => 'A Note'
            ]);

        ...
    }
}

This will render form fields with names like app_task[title] and app_task[note]. Is it possible to use custom names instead?

Sure, Symfony uses the identify the properties and map the input to the entity. However, it should not be to hard to specify a different name by mapping the field to a different name or vice versa by mapping a field name to the entity property.

Something like this:

$builder
    ->add('title', TextType::class, [
        'label' => 'The Title',
        'renderedName' => 'customTitleName',
    ])        
    ->add('note', TextType::class, [
        'label' => 'A Note'
        'renderedName' => 'customNoteName',
    ]);

OR

$builder
    ->add('customTitleName', TextType::class, [
        'label' => 'The Title',
        'mappedFieldName' => 'title',
    ])        
    ->add('customNoteName', TextType::class, [
        'label' => 'A Note'
        'mappedFieldName' => 'note',
    ]);

I could not find such a solution. So, is it somehow possible to use custom field names?


Solution

  • Possible solution is to use property-path

    $builder
        ->add('customTitleName', TextType::class, [
            'label' => 'The Title',
            'property_path' => 'title',
            'renderedName' => 'customTitleName',
        ])        
        ->add('note', TextType::class, [
            'label' => 'A Note'
            'renderedName' => 'customNoteName',
        ]);