this question may sound a bit newbie. What I am trying to do is to show a form inside a view, create an object and submit it.
My list view shows a list of existing objects and I showed a new/create button that brings the form which creates a new object calling the controller.
I don't know if there is a more proper way to do this but I came up with this code that works partially. The code works when my url is /new (showing only the form), however while it is /list it doesn't work.
List view (only relevant code):
{# AppBundle/Resources/views/list.html.twig #}
<div id="info">
<button type="button" onClick="new()">New Object</button>
</div>
<script>
function new() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("info").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "/new", true);
xhttp.send();
}
</script>
New view:
{# AppBundle/Resources/views/new.html.twig #}
{{ form(form) }}
Controller methods:
// AppBundle/Controller/ObjectController
public function newAction(Request $request)
{
$object = new Object();
$form = $this->createFormBuilder($object)
->add('Text', 'textarea')
->add('save', 'submit')
->getForm();
$form->handleRequest($object);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($object);
$em->flush();
return $this->redirectToRoute('list');
}
return $this->render('AppBundle:new.html.twig', array(
'form' => $form->createView(),
));
}
public function listAction(Request $request)
{
$objects = $this->getDoctrine()
->getRepository('AppBundle\Entity\Object')
->findAll();
return $this->render('AppBundle:list.html.twig', array(
'objects' => $objects,
));
}
Thanks a lot for your time!!