How to get the information of an entity through select2 (after selection) in Symfony 5 / AJAX

So long story short, I have two entities, Client and Contacts of a Client in a OneToMany relationship.

What I want to do is this :

When creating a new contact for an unknown (yet) client I have to select a Client for this contact.

So when I select the client for this contact in my form, I want the information of the client to pop out below the form for the new contact. So here’s what I did

The Controller :

 /**
 * @Route("/new", name="unset_client_new_contact", methods={"GET","POST"})
 */
public function new(Request $request, ClientRepository $cr): Response
{
    $contact = new Contact();
    $form = $this->createForm(UnsetClientContactType::class, $contact);
    $form->handleRequest($request);

    if ($request->isXmlHttpRequest()) {
        $idClient = $request->request->get('id');
        $client = $cr->findOneBy(['id' => $idClient]);
        $response =  new JsonResponse([
            'name' => $client->getName(),
            'adress' => $client->getAdress(),
            'city' => $client->getCity(),
        ]);
        dump($response);
        return $response;
    }

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($contact);
        $entityManager->flush();
        return $this->redirectToRoute('contact_index');
    }

    return $this->render('contact/new.html.twig', [
        'contact' => $contact,
        'form' => $form->createView(),
    ]);
}

(I’m not using serializers and stuff it gives me circular references error so I use JsonResponse to use in AJAX and that’s the main issue)

And here is the view :

{% extends 'base.html.twig' %}
{% block title %}Add contact{% endblock %}
{% block body %}
<h2><i class="text-success fas fa-plus"></i>Add a contact</h2><hr><br>
    {{ include('contact/_form.html.twig') }}
    <div class="col-md-4">
        <a class="btn btn-info btn-block form-rounded" href="{{ path('contact_index') }}">Back to list</a>
    </div>
</div>
{% if client is defined and client is not null %}
<hr>
<h1> Reminder of {{ client.name }} </h1><br>
<table id="contact" class="table table-bordered table-sm text-center text-justify table-striped">
    <tbody>
        <tr>
            <th>Name</th>
            <td>{{ client.name }}</td>
        </tr>
        <tr>
            <th>Adress</th>
            <td>{{ client.adress }}</td>
        </tr>
        <tr>
            <th>City</th>
            <td>{{ client.city }}</td>
        </tr>
    </tbody>
    {% endif %}
{% endblock %}
{% block javascripts %}
<script>

$(document).ready(function() {
    $('#unset_client_contact_client').select2({
        placeholder: "Search an Existing Client",
        allowClear: true
    });
    
});

var $client = $('#unset_client_contact_client');
$client.on('select2:select', function (e) {
    var $form = $(this).closest('form');
    id = e.params.data.id
    console.log(id);
    var data = {};
    $.ajax({
        url : $form.attr('action'),
        type: $form.attr('method'),
        data : 
            {
                id:id
            },
        success: function(html) {
        }
    });
});
</script>
{% endblock %}

And here’s a picture of the dump

Dump of the $response, the dump occurs after I select a client in my form

So the question is how do I use the values I get in my dump (see picture above) in my HTML/jQuery/TWIG ? Because if I write for example :
var response = {{response}} I just get an error that {{response}} doesn’t exist.
I can’t seem to figure it out so if someone has the solution i’ll gladly take it.

Thank you for reading me.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *