1
votes

I'm rewriting old deprecated REST API on Symfony and problem is how to map and validate fields with different names on Symfony form.

An example I have Symfony form, with fields:

->add('receiverCity', TextType::class, ['constraints' => new NotBlank()])
->add('receiverCountry', TextType::class, ['constraints' => new NotBlank()])
->add('receiverPostCode', TextType::class, ['constraints' => new NotBlank()])

and in Controller from request I get same fields with different names like:

$data = ['city' => 'My city', 'country' => 'My country', 'postal' => 'My post code'];

Then I submit form manually $form->submit($data). And question is what is the best way to map and validate this field in form? Should I use form events or there is a simpler way to do that?

1

1 Answers

4
votes

You can use the property_path option. (Also see Symfony documentation for more information).

You would need to use the "old" field names as form field names and set the property_path to the actual field name within the object:

->add('city', TextType::class, 
    [
        'constraints' => new NotBlank(),
        'property_path' => 'receiverCity'
    ]
)
->add('country', TextType::class,
    [
        'constraints' => new NotBlank(),
        'property_path' => 'receiverCountry'
    ]
)
->add('postal', TextType::class, 
    [
        'constraints' => new NotBlank(),
        'property_path' => 'receiverPostCode'
    ]
)