Reputation: 46
I'm trying to make a tabs nav with a central block that contains a Symfony form.
When I click into a link in a tab navs, I reload the block with form and data.
But the issue is how to pass formView object from the first twig to the AJAX twig response view?
My controller
/**
* @Route("/change-tab/{tabId}", name="change_tab")
* @param Request $request
* @return Response
*/
public function changeTab(Request $request, $tabId): Response
{
$firstElement = $this->getDoctrine()->getRepository(Element::class)->findOneBy([
'cart'=>$tabId,
]);
return $this->render('partials/_bloc-cart.html.twig',[
'firstElement '=> $firstElement ,
//'form' => $request->getContent()
]);
}
My twig view
<div class="row p-2">
<div class="col-md-12 px-0" id="bloc-form">
{{ include('partials/_form.html.twig') }}
</div>
</div>
And the ajax JS :
$(document).on('click', '.linkToChange', function () {
$('.linkToChange.active').removeClass('active');
$(this).addClass('active');
let formPlan = $('#bloc-form').data('form');
$.ajax({
type: "POST",
data : formPlan,
url: "/ajax/change-tab/" + $(this).data('cart'),
success : function (datas) {
$('#bloc-form').html(datas);
}
});
});
Upvotes: 0
Views: 939
Reputation: 120
You can try:
/**
* @Route("/change-tab", name="change_tab", method="{POST}")
* @param Request $request
* @return Response
*/
public function changeTab(Request $request)
{
$tabId = $request->get('tab_id');
$firstElement = $this->getDoctrine()->getRepository(Element::class)->findOneBy([
'cart'=>$tabId,
]);
$html = $this->render('partials/_bloc-cart.html.twig',[
'firstElement '=> $firstElement ,
//'form' => $request->getContent()
]);
return $this->json(['html' => $html]);
}
Jquery:
$.ajax({
type: "POST",
data : formPlan,
url: "{{ url('change-tab') }}",
dataType: 'json',
data: {
'tab_id' : $(this).data('cart'),
}
success : function (data) {
$('#bloc-form').remove();
$('#bloc-form').html(data.html);
}
});
Upvotes: 0
Reputation: 449
You have different ways to do it, if you use the Form Component, you can do something like this:
public function changeTab(Request $request, $tabId): Response
{
$firstElement = $this->getDoctrine()->getRepository(Element::class)->findOneBy([
'cart'=>$tabId,
]);
$form = $this->createForm(ElementType::class, $firstElement);
$form->handleRequest($request);
// Save if form is submitted and valid
return $this->render('partials/_bloc-cart.html.twig',[
'firstElement '=> $firstElement ,
'form' => $form->createView()
]);
}
Upvotes: 1