Symfony2 send form ajax

♀尐吖头ヾ 提交于 2019-12-04 02:42:21

I suggest to pass the id to the controller.

html:

<form class="ajax" action="{{ path('ajax_setSocial', { 'id': entity.id }) }}" method="post" {{ form_enctype(form) }}>

var url = "{{ path('ajax_setSocial', { 'id': entity.id }) }}";

The controller annotation, parameter, and return value, to get the id:

/**
 *
 * @Route("/{id}", name="ajax_setSocial")
 * @Method("POST")
 */
public function setSocialeAction(Request $request, $id) {
    $em = $this->getDoctrine()->getManager();
    $entity = $em->getRepository('MyBusinessBundle:Anagrafic')->find($id);

    return array(
        'entity' => $entity
    );
}

Passing error back to html is like this:

// dummy line to force error:
// $form->get('ragSocial')->addError(new FormError("an error message"));

if ($form->isValid()) {
    ...
} else {
    $errors = $form->get('ragSocial')->getErrors(); // return array of errors
    $output[] = array('error' => $errors[0]->getMessage()); // the first error message
    $response->headers->set('Content-Type', 'application/json');
    $response->setContent(json_encode($output));
    return $response;
}
Lighthart

I think you want this:

symfony2 chained selectors

However, this one may also be useful:

Many-to-Many Ajax Forms (Symfony2 Forms) (Answer 3)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!