How can you leverage Symfony to iterate through a JSON array efficiently?

After selecting a user, I am attempting to display a list of contracts. To achieve this, I have written the following query:

    /**
 * @param $firstname
 * @param $lastname
 * @return mixed
 * @throws DBALException
 */
public function getListPerUser($firstname, $lastname)
{
    $em = $this->getEntityManager();

    $query = '
        SELECT clientname 
        FROM contact_end_client c
        INNER JOIN client_contract cli ON cli.clientname_id = c.id AND  cli.active
        INNER JOIN user u ON u.id = cli.user_id
        WHERE u.firstname = :firstname AND u.lastname = :lastname AND cli.active = 1
        ';

    $stmt = $em->getConnection()->prepare($query);
    $param = ['firstname' => $firstname, 'lastname' => $lastname];
    $stmt->execute($param);
    return $stmt->fetchAll();
}

Below is my controller code:

    /**
 * @Route(path="/newadmin/invoice/showAllContract", name="showAllContract")
 * @param Request $request
 * @return JsonResponse
 */
public function viewContract(Request $request)
{
    $entityManager = $this->getDoctrine()->getManager();
    $template_id = $request->get('user');
    //dump($template_id);
    $getName = explode(" ", $template_id);
    $firstname = $getName[0];
    $lastname = $getName[1];
    $templateRepository = $entityManager->getRepository(ClientContract::class)->getListPerUser($firstname, $lastname);
    return new JsonResponse($templateRepository);
}

The above code will return a JSON response. To iterate over it and display in Twig, refer to the following snippet:

{{ form_start(createInvoice) }}
            {{ form_row(createInvoice.user) }}
            {# your contract #}
            {{ form_end(createInvoice) }}
        </div>
    </div>
</div>
<script>
    $(document).ready(function () {
        $('#invoice_manual_creation_user').change(function (message) {
            $('#hidden').show();

            let userName = $('#invoice_manual_creation_user option:selected').text();
            console.log(userName)

                $.get("{{ path('showAllContract') }}", {'user': userName})

        });
    });
</script>

Answer №1

{{ form_start(createInvoice) }}
            {{ form_row(createInvoice.user) }}
           <ul id="my-contract-list">
               
           </ul> 
            {{ form_end(createInvoice) }}
        </div>
    </div>
</div>
<script>
    $(document).ready(function () {
        $('#invoice_manual_creation_user').change(function (message) {
            $('#hidden').show();

            let userName = $('#invoice_manual_creation_user option:selected').text();
            console.log(userName);
            
            const url = "{{ path('showAllContract',{'user': "+userName+"}) }}";

                $.get(url,function(data) {
                        var myContractListUl = $("#my-contract-list");

                        // if the data is empty
                        if (data.length === 0) { 
            
                            var li = $('<li></li>').text('Contracts not found');
                            myContractListUl.append(li);
                            return;
                        }
                        
                        // Iterate through the data, create a list item for each item, and append it to the ul element
                        $.each(data, function(index, item) {
                            var li = $('<li></li>').text(item.clinentName);
                            myContractListUl.append(li);
                        });
                });

        });
    });
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`In HTML, trigger blocks based on the number chosen by the user`

I am working on creating a web page where users can select the number of friends they have, and based on that input, a corresponding number of invisible boxes will be triggered. For example, if a user selects 3 friends, 3 boxes will appear for them to ente ...

Enhancing bar chart presentation with text in d3

Looking to enhance my bar chart by adding text tooltips that appear when hovering over each bar. While I am a beginner with d3, I've been struggling to implement this feature effectively. Despite trying various methods gleaned from online resources, t ...

Uncharted Territory: Exploring asynchronous loops with async await and Promise.race?

Currently, I am involved in a project that requires brute forcing a PDF password. To achieve this task, I am using PDF.js to verify the password and implementing promise.race to execute parallel functions for efficient performance. This is how I have str ...

Utilizing Ajax to dynamically submit specific form fields

I'm just starting out with Jquery ajax, and I'm experimenting with submitting specific fields for validation instead of the entire form. I've created a function to check if a username is available, and it's working well. However, I want ...

Jasmine is having trouble scrolling the window using executeScript

I usually use the following command: browser.driver.executeScript('window.scrollTo(0,1600);'); However, this command is no longer working. No errors are showing in the console, making it difficult to troubleshoot. Interestingly, the same scri ...

Discover the ultimate guide to creating an interactive website using solely JavaScript, without relying on any server-side

I'm facing a challenge: I have a desire to create a website that is mainly static but also includes some dynamic components, such as a small news blog. Unfortunately, my web server only supports static files and operates as a public dropbox directory. ...

Scrolling infinitely in every direction - both upwards and downwards

I'm currently working on a page that I want to have an endless scrolling effect both up and down. Right now, I am using jQuery to move content from the top of the page to the bottom. This gives a smooth loop when scrolling down, but I also want it to ...

shallow rendering does not recognize this.props as a function

I'm currently facing an issue while trying to test my (legacy) component using jest/enzyme. Here is a snippet of the component: export default class MyComponent extends Component { constructor( props ) { super( props ); this.handl ...

Successfully received response from Ajax post - unable to display on screen

After successfully posting data to the server using $.post(), I am encountering issues when trying to work with the response. Unfortunately, nothing appears - no console log is shown and I am unable to replace text or HTML with the retrieved data. Below i ...

The resolution of the Ajax call promise remains elusive

When I make an AJAX call to a REST API in my JavaScript code, the purpose is to fetch a JSON file. The structure of the AJAX call resembles something like this: $.ajax(ajaxObj).then(function(response) {}).catch(function(err) {}); The network monitor refl ...

Guide to updating a database using ajax and javascript in asp.net mvc without the need to refresh the page

Is there a way to update the value of an enumdropdownlist from "active" to "inactive" in my database through an ajax call without having to refresh the page? I am unsure whether to use a javascript method or ajax.beginform for this task. I attempted to us ...

How to Develop a Custom getText() Function for a Selenium Element?

Creating a custom Selenium getText() method that can retrieve either the node text or the node plus child text of an element is my current challenge. The default behavior of Selenium appears to utilize the Xpath .//string() method which includes the text o ...

What is the best way to utilize an onClick on a button to update a value that is being utilized in a useEffect hook?

I am looking for a way to dynamically change the content displayed in this section without navigating to another page. I have two sets of data - one displaying all blogs and the other showing only blogs authored by "mario". How can I implement a button cli ...

The PHP file on the server is missing the mandatory "event" parameter for the EventSource

Explaining this issue was a bit of a challenge. I've set up a Javascript EventSource object with some customized event handlers like so: var source = new EventSource('updates.php'); source.addEventListener('add', addHandler, fals ...

Ensure UseEffect is only triggered once with specific dependencies

Whenever the component is loaded, I have a method called useEffect() that runs once. useEffect(() => { (async function fetchData() { const results = await stateIsoAPI(); setStates(results); // API results to trigger other Use effect ...

Wrangler of RESTful services with mongoDB, I am currently grappling with the challenge of converting BSON values to JSON

I'm currently utilizing cowboy for RESTful services with mongoDB. I encountered an error related to BSON value to JSON conversion (specifically '_id' in mongodb value). Does anyone have any ideas on how to retrieve mongoDB documents, convert ...

What is the best method to customize CSS in ExtJS 5.0 by overriding a function?

Is there a way to dynamically add a rule to existing CSS using code, particularly in overrides? For example: var sheets = document.styleSheets; // Some code omitted for simplicity var sheet = sheets[sheets.length - 1]; sheet.insertRule('.overlay {flo ...

Exploring the Power of Streams in JavaScript

I'm looking to create a stream object that can perform the following actions: // a -------1------2----3 // map -----\------\----\ // b --------2------4----6 const a = new Stream(); const b = a.map(value => value * 2); b.subscribe( ...

Vuetify's personalized date selection tool

Utilizing Vuetify's v-date-picker in multiple components can result in code repetition. To address this, I decided to create a custom <custom-date-picker /> component that can be used wherever needed. This child component should em ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...