Gareth
Gareth

Reputation: 102

OctoberCMS - How to make component data available in javascript

I need to dynamically fill data for a dashboard theme but I am unsure how to do this. So far my code looks like this.

Component:

public $orders;

public function onRun() {
    $this->orders = $this->loadOrders();
}

protected function loadOrders() {
    $all_customers = Db::table('customers')->get();

    foreach ($all_customers as $customer) {

    }

    $orders = Db::table('orders')->where('company_name', $customer->company_name)->count();

    return $orders;
}

From this I get the amount of orders in the system for that customer which works fine but its the next part I am struggling with. This is my my javascript:

var PIECHART = $('#pieChart');
var orders = ** This is where I am lost **;
var quotes = ** This is where I am lost **;
var invoices = ** This is where I am lost **;
var myPieChart = new Chart(PIECHART, {
    type: 'doughnut',
    data: {
        labels: [
            "Orders",
            "Quotes",
            "Invoices"
        ],
        datasets: [
            {
                data: [orders, quotes, invoices],
                borderWidth: [1, 1, 1],
                backgroundColor: [
                    brandPrimary,
                    "rgba(75,192,192,1)",
                    "#FFCE56"
                ],
                hoverBackgroundColor: [
                    brandPrimary,
                    "rgba(75,192,192,1)",
                    "#FFCE56"
                ]
            }]
    }
});

I am pretty sure the solution is fairly straight forward but I am a noob :P

Upvotes: 0

Views: 632

Answers (1)

Hardik Satasiya
Hardik Satasiya

Reputation: 9693

We assume that you are directly using this component in page

so what you need to do is just try to use

public function onRun() {
    $this->page['orderCount'] = $this->loadOrders();
}

now in your page you need to make this variable available to the js

<script>
// we don't want to pollute global scope so we add our name space
var myComponent = myComponent || {}
// now we add our value to it 
myComponent['orderCount'] = {{ orderCount }};
</script>

above code will generate, suppose we get counter is 15 then

myComponent['orderCount'] = 15;

now in your javascript you can use this like

var PIECHART = $('#pieChart');
var orders = myComponent['orderCount']; // or myComponent.orderCount
var quotes = ** This is where I am lost **;
var invoices = ** This is where I am lost **;

this works well for number but if you also need to share array to java-script you need to convert it to JSON and then you can use it

let me know if you need further assistance

Upvotes: 1

Related Questions