What is the process for including a collection of objects in chartjs?

Is there a way to add an array of objects to chartjs? In the controller of the view, an array is passed to the Twig template using the variable {{cg}}. However, I am encountering an error that suggests the array I am working with is actually an array of arrays. My aim is to populate the labels attribute with a list of months and the data attribute with the corresponding amount. Any suggestions on how to achieve this? Below is the snippet from the controller:

/** Controller
 * @Route("/cg1", name="cg1")
 */
public function cg1Action()
{
    $conn=$this->get('database_connection');
    $consulta="SELECT consumo_combustible.importe as imp,MONTH(consumo_combustible.fecha) as mes FROM consumo_combustible WHERE YEAR(consumo_combustible.fecha)=2018";
    $sql=$conn->fetchAll($consulta);      
    return $this->render('default/consultag1.html.twig', array('cg' => $sql));
}

//-------------- //- AREA CHART - //--------------

         // Get context with jQuery - using jQuery's .get() method.
         var areaChartCanvas = $('#areaChart').get(0).getContext('2d')
         // This will get the first returned node in the jQuery collection.
         var areaChart       = new Chart(areaChartCanvas)
         var datames = []
         datames={{ cg.mes }} ;
         var dataimp = [] ;

         dataimp={{ cg.imp }} ;
         var areaChartData = {
             labels  : datames,
             datasets: [
                 {
                     label               : 'Electronics',
                     fillColor           : 'rgba(210, 214, 222, 1)',
                     strokeColor         : 'rgba(210, 214, 222, 1)',
                     pointColor          : 'rgba(210, 214, 222, 1)',
                     pointStrokeColor    : '#c1c7d1',
                     pointHighlightFill  : '#fff',
                     pointHighlightStroke: 'rgba(220,220,220,1)',
                     data                :  dataimp
                 },
                 {
                     label               : 'Digital Goods',
                     fillColor           : 'rgba(60,141,188,0.9)',
                     strokeColor         : 'rgba(60,141,188,0.8)',
                     pointColor          : '#3b8bba',
                     pointStrokeColor    : 'rgba(60,141,188,1)',
                     pointHighlightFill  : '#fff',
                     pointHighlightStroke: 'rgba(60,141,188,1)',
                     data                :  dataimp
                 }
             ]
         }

An error is thrown indicating:

Key "mes" for array with keys "0, 1, 2, 3, 4, 5" does not exist in default\consultag1.html.twig at line 55

Answer №1

Here is the solution: by using the raw function {{result | raw}}, I am able to extract the data sent from the controller to the view.

  var monthValues=[];
  var amountValues=[];  

  //arr= [{"imp":"3000","mes":"2"},{"imp":"830","mes":"3"},{"imp":"1900","mes":"4"}];

  var arr= JSON.parse('{{ resultado|raw }}');

  for(var i=0; i< arr.length; i++){
       monthValues[i]=arr[i].mes;
       amountValues[i]=arr[i].imp;
  }

  console.log(monthValues);

  console.log(amountValues);


  var areaChartData = {

  labels  :  monthValues,
  datasets: [
    {
      label               : '2018',
      fillColor           : 'rgba(210, 214, 222, 1)',
      strokeColor         : 'rgba(210, 214, 222, 1)',
      pointColor          : 'rgba(210, 214, 222, 1)',
      pointStrokeColor    : '#c1c7d1',
      pointHighlightFill  : '#fff',
      pointHighlightStroke: 'rgba(220,220,220,1)',
      data                : amountValues
    }

  ]
}

 /**
 * @Route("/cg1", name="cg1")
 * @Method({"GET", "POST"})
 */
public function cg1Action(Request $request)
{
    $conn=$this->get('database_connection');
    $query="SELECT SUM(consumo_combustible.importe) as imp, MONTH(consumo_combustible.fecha) as mes FROM consumo_combustible WHERE YEAR(consumo_combustible.fecha)=2018 GROUP BY consumo_combustible.fecha";
    $queryResult=$conn->fetchAll($query);
    $jsonResponse = json_encode($queryResult);

    echo($jsonResponse);
    return $this->render('default/consultag1.html.twig',array(
        'response' => $jsonResponse

    ));
}

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

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

What is the method of updating content on a webpage without altering the page itself or using hashed URLs?

I have a good understanding of how to update webpage content through AJAX and loading remote content. However, I recently came across UStream's innovative new layout. When you click on any video, not only does the content change seamlessly without rel ...

`The functionality of parent.location is not operating as expected in Firefox and Chrome, however, it is functioning

Issue with JSP: <A NAME="CustomerInformation"></A> <table class="SectionHeader1"> <TBODY>enter code here <tr> <td>Customer Information</td> </tr> </TBODY> </table ...

jQuery Issue - Clash between multiple menus sharing the same class

Hey there! I'm currently diving into the world of jQuery and encountering an issue with my menu. Whenever I click on a menu item with either the "tm-nav-vertical" or "tm-nav-horizontal" class, it removes the .active class from the initial menu item. I ...

Experiencing issues while attempting basic private key encryption with the Node crypto library

Currently, I am in the process of creating a quick proof of concept (POC) to encrypt an incoming string using a standard key. Below is the code snippet from my middleware: import Crypto from 'crypto'; export default async function encrypt(req, r ...

It appears that the home page of next.js is not appearing properly in the Storybook

Currently, I am in the process of setting up my next home page in storybooks for the first time. Following a tutorial, I successfully created my next-app and initialized storybooks. Now, I am stuck at importing my homepage into storybooks. To achieve this, ...

Is it possible to leverage the flex features of react-native in a manner similar to the row/column system of

Is it a good idea to utilize flex in react native by creating custom components that retrieve flex values? I previously used the bootstrap grid system and now I am exploring react native. Is there a way to implement this example using react-native bootstr ...

Transferring data from a React file to a plain HTML page

What is the best way to transfer information from a React app to a static HTML file? For instance, if I collect data through a form in a React app.js file, how can I then send that data to a basic HTML file? ...

Displaying a Modal with a Click Action

I am encountering a challenge in displaying a modal when clicked using onClick(). In a component, I have a function that adds players to a list when the Add Player button is clicked. This button is generated separately in a function called renderAddButton( ...

Activate jQuery function upon clicking a bootstrap tab

When I click on a Bootstrap tab, I want to trigger an AJAX function. Here is the HTML code: <li><a href="#upotrebljeni" data-toggle="tab">Upotrebljeni resursi</a></li> The jQuery AJAX function looks like this: $('a #upotreb ...

Limit not reached by substring function

When the character limit exceeds 20 characters, the substring function extracts the first 20 characters typed in the input. It replaces any additional characters that are entered after reaching the max limit of 20. In my program, however, I am able to con ...

Encountering issues with Yarn Install during production build. Issue states: "Error - [email protected] : The engine "node" does not align with this module"

Currently facing an issue while deploying a ReactJS Project on the PROD environment. The previous command "Yarn install" was working fine, but now it's failing with an error message. The error that I'm encountering is: info [email protected ...

Making an input field in Vue automatically read-only when a specific value is met

Is it possible to make an input field read-only in Vue.js based on data values? Here's a situation: <select class="form-control" id="selectCategory" :readonly="cat_id >= 1" name="cat_id"> I'm looking for a wa ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

Is there a way to stop a specific route in Express from continuing further execution without completing its function?

In my post route, I need to ensure that the user has provided all the necessary data in the body. To achieve this, I have added an if block to check for errors. router.post("/", (req, res) => { if(req.body.age < 24) { res.send("You are too you ...

multiple elements sharing identical CSS styling

For each component, I made separate CSS files and imported them accordingly. However, despite the individual styling efforts, all components seem to have the same appearance. I specifically worked on styling an image differently for two components, but w ...

Is it possible to obtain a Median value using SQL?

Is this query designed to provide the median salary for each company? SELECT a.id,a.company_name,a.salary FROM (SELECT id,company_name,salary,PERCENT_RANK() OVER(PARTITION BY company_name ORDER BY salary) AS 'percentile') a WHERE percentile = 0. ...

Utilizing jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Adding data to an array from a JSON source using Angular 5

When I receive a response from an endpoint, it looks like this: { "data": [{ "volume": 4.889999866485596, "name": "Carton03", "weight": 5.75, "storage": 3 }, { "volume": 2.6500000953674316, "name": "Carton02", "weight": 4.5 ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...