PHP Symfony Forms How to access Properties in nested objects

2.6k Views Asked by At

I am creating several forms with Symfony and the FormBuilder. Normally I provide a flat object that holds all properties the form needs to access. This works fine. The form fills the object with the correct values and I can send it as json to a webservice wher it is processed (so I don't access a database at all). But in several cases I got nested objects from the webservice that have to be updated or I have to send nested objects (as json) to the service and I wonder if it is possible to access properties of nested objects within the form.

Normally you do

$form = $this->createFormBuilder($myObject)
->add('myProp', 'text', array(
    'label'=>$this->get('translator')->trans('my Property')
))

But in my case myObject holds another object where some properties are located. So I would need to do something like this:

$form = $this->createFormBuilder($myObject)
->add('nestedObj.myProp', 'text', array(
    'label'=>$this->get('translator')->trans('my Property')
))

But unfortunately this does not seem to work. Is there another solution to deal with nested objects and forms?

1

There are 1 best solutions below

0
On

Dots are not allowed in field names (the reason for this lies in the details of the HTML specification). However, you can override the "property_path" option to customize the used property path:

$form = $this->createFormBuilder($myObject)
    ->add('myProp', 'text', array(
        'label' => $this->get('translator')->trans('my Property'),
        'property_path' => 'nestedObj.myProp',
    ))