I am using Symfony, version 2.5.3, and I am trying to submit a form using Ajax. So in my controller I have
$form = $this->createForm(
new MyFormType(),
$formvariable
);
$form->handleRequest( $request );
if ($form->isValid()) {
} else {
}
and my jQuery script might look like this:
formdata = $('form[name=MyFormTypeForm]').serialize();
$.ajax({
type: "POST",
url:
data: formdata ,
async: true,
dataType: "json",
success: function(response)
{
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
},
});
This will work fine, but unfortunately I have to send other variables along with the form fields.
What I want to do in my jQuery looks something like this:
formdata = $('form[name=MyFormTypeForm]').serialize();
value = {
myvar1 : data1 ,
myvar2 : data2 ,
formdata : formdata ,
};
$.ajax({
type: "POST",
url:
data: value ,
async: true,
dataType: "json",
success: function(response)
{
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
},
});
However, this way $form->isValid()it always returns false inside the controller.
Is there any way to fix this?
Thank you in advance
Alberto
Edit:
Add additional information in response to the comments:
I cannot add additional fields inside my form because additional variables are used to create the form itself.
:
$em = $this->getDoctrine()->getManager();
$action = $request->request->get('action', null);
$myentid = $request->request->get('myentid', null);
if ( empty($myentid) )
{
$formvariable = new MyEntity();
} else {
$formvariable = $this->getDoctrine()->getManager()
->getRepository('MyBundle:MyEntity')
->find($myentid);
}
$form = $this->createForm(
new MyFormType(),
$formvariable
);
if ($action == "newform")
{
$response["code"] = $this->render('MyBundle:Controller:mytwigview.html.twig', array(
'form' => $form->createView(),
))->getContent();
return new Response(json_encode($response));
}
if ($action == "save")
{
$form->handleRequest( $request);
if ($form->isValid()) {
$em->flush();
} else {
echo "Errors: ".$form->getErrors();
}
}