Decision:
The solution to my problem was to create several additional functions in the controller in order to solve the problem where I want to be able to change the essence and form on the fly from the selection by the user.
public function indexAction(Request $request) { $form = $this->getForm($request); $form->handleRequest($request); return array( 'form' => $form->createView(), 'request' => $request->request, ); }
Where getForm retrieves the form (for example, AdvertVehicleType for vehicles or Ad type for the default ad).
The getForm method is as follows:
private function getForm(Request $request) { $categoryTitle = 'NONE'; $categoryId = $request->request->get('advert', false)['category']; if ($categoryId) { $categoryTitle = $this->getDoctrine()->getRepository('Bundle:Category')->find($categoryId)->getTitle(); } return $this->createForm($this->getFormType($categoryTitle), $this->getEntity($categoryTitle));
}
here I extract the categoryID (which is selected on the form in the request) and returns the type of the form with getFormType and the object with getEntity.
private function getEntity($categoryTitle) { $entity = new Advert(); switch ($categoryTitle) { case Category::CARS: $entity = new AdvertCar(); } return $entity; } private function getFormType($categoryTitle) { switch ($categoryTitle) { case Category::CARS: return new AdvertCarType(); default: return new AdvertType(); } }
To update this on the fly using ajax (but it also works if the user tries to submit the form), I created another action in the controller.
This action displays the parts of the form that I want to update (when calling ajax), I do this by actually choosing what I donβt need in the form with a branch, setting the form objects to display as follows:
{% do form.title.setRendered %}
(this is just an example that I actually do for all form objects that I don't want to display.
Then I just call:
{{ form_rest(form) }}
which will retrieve the "remainder" of the form, which is different for different categories.
Now let me say that you have a state, not a city. First select a state, after which you will create cities for this state in the branch (but then you can just display the part you need, for example {{ form_row(form.towns) }} , and return this processed template as json-response and just put it in a div want with jquery.
$html = $this->renderView('@Bundle/NewAddPage/filter_area.twig', array('form' => $form->createView()));
and then returns the $ html variable in the response.
I hope this helps, and that the explanation is good enough, if not just a comment, and I will update it with my answer!