Search code examples
javascriptdatabasesymfonycommunication

Passing database values to JavaScript under Symfony?


I am creating an autocomplete tool for a specific input field in a form. The autocomplete is fed by a JavaScript array containing the values to suggest, and it works the way I want with fake values. But now, I want to feed the array with actual values from my MySQL database, meaning I have to get my DB's values (an entire column's values, it happens) to this array somehow. Note that I only need to store these values once, like when the page loads.

I've been browsing a lot, but haven't tried anything by lack of understanding of the code and mechanisms. The answer I need is close to what this thread is suggesting, but I couldn't understand how the OP linked his controller to his JavaScript (storing the value of an HTML element with the ID "categories-fetch" in a JS variable seems a bit insufficient to me, if not irrelevant).

I am using HTML-CSS-JS for the front end, Symfony and Doctrine for the back-end and DB communication with MySQL. Any ideas?

SOLUTION EDIT:

With help from @Davis, managed it with a method that gets the data:


Solution

  • I can't add a comment yet!

    I hope this article can help you

    creating templates

    // php
    return $this->render('xx/xx/xx.html.twig', [
        'data' => [
            'name' => 'davis',
            'age' => 18,
            'sex' => 'M'
        ]
    ]);
    
    // twig
    <select id="ice-cream-flavors">
        {% for column, value in data %}
            <option value="{{ value }}">
        {% endfor %}
    </select>