2

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?

4
  • This seems to be a duplicate of this previously answered question Commented Dec 13, 2013 at 10:45
  • 1
    Have you read through the forms manual? Nested objects are very common. You just need to make a form type specific to each entity type. ->add('nestedObj',new NestedObjFormType()) Commented Dec 13, 2013 at 14:18
  • Just a note but you don't need to use the translator. You can just write the property and translator will work automatically. Commented Dec 16, 2013 at 0:54
  • Thank you very much. As symfony is still new to me that was very good help. Commented Dec 16, 2013 at 13:49

1 Answer 1

7

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

Comments

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.