11

I'm trying to submit a form via ajax to update a field of an entity, but do not know how to retrieve the data from the controller:

<form class="ajax" action="{{ path('ajax_setSocial') }}" method="post" {{ form_enctype(form) }}>
  <div class="editor">
        {{ form_errors(form) }}
        <div class="editLabel pls">{{ form_label(form.ragSocial) }}</div>
        <div class="editField"> 
            <div class="ptm">
                {{ form_widget(form.ragSocial) }} {{ form_errors(form.ragSocial) }}
            </div>     
            {{ form_rest(form) }}
            <div class="mtm">
                <button class="btn btn-primary disabled save" type="submit">Save</button>
                <button class="btn ann">Close</button>
            </div>
        </div>
  </div>

  var url = Routing.generate('ajax_setSociale');
        var Data = $('form.ajax').serialize();
        $.post(url, 
            Data
            , function(results){
                if(results.success == true) {
                    $(this).parents('ajaxContent').remove();
                    $(this).parents('.openPanel').removeClass('openPanel');
                } else {
                    alert('False'); //test
                }
        });

controller (ajax_setSocial route)

public function setSocialeAction(Request $request)
{
      $em = $this->getDoctrine()->getManager();
      // $id = $request->get('form'); ???
    $entity = $em->getRepository('MyBusinessBundle:Anagrafic')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Anagrafic entity.');
    }

    $form = $this->createFormBuilder($entity)
       ->add('ragSocial', 'text', array('label' => 'Social'))
       ->add('id', 'hidden')
        ->getForm();
    $form->bind($request);

    if ($form->isValid()) {
        $em->persist($entity);
        $em->flush();

        $output = array();
        $response = new Response();
        $output[] = array('success' => true);
        $response->headers->set('Content-Type', 'application/json');
        $response->setContent(json_encode($output));
        return $response;
    }

As recovery values ​​and then pass the id to create the query and the other values ​​to update the entity? And if the fields do not pass validation, how do I pass the error?

2 Answers 2

7

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I followed this approach and it is working. Many thanks. I only have one issue, Controller requires that you provide a value for the "$id" argument (because there is no default value or because there is a non optional argument after this one). Can you please help me with this issue?
@whitelettersandblankspaces in symfony2.3 you can set default value in your controller like that public function setSocialeAction(Request $request, $id = 1). In 2.0 or before 2.3 (not sure) set it in annotation: @Route("/{id}", name="ajax_setSocial", defaults={"id"=1})
1

I think you want this:

symfony2 chained selectors

However, this one may also be useful:

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

1 Comment

Maybe I explained bad, I'm trying to figure out how to use the parameters received from the form, and then validate and return errors if present, otherwise "true"!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.