Ad

OctoberCMS Working With Arrays

- 1 answer

I am having some trouble understanding how to work with arrays, I am trying to build an invoice where by it returns the price and details of an order, I have most of it working but I would like to display the items of the order. so far my code looks like this:

public $items;

public function prepareVars() {
    $this->items = $this->items();
}


public function items() {
    $plates = Db::table('orders')->where('quote_no', $this->quoteNo())->value('total_plate_qty');
    $hires = Db::table('orders')->where('quote_no', $this->quoteNo())->value('req_hires');
    $hardcopy = Db::table('orders')->where('quote_no', $this->quoteNo())->value('req_hardcopy_proof');
    $pdfproof = Db::table('orders')->where('quote_no', $this->quoteNo())->value('req_pdf_proof');
    if ($plates < 1) {
        $plates = "Total Plates:" . $plates;
    } else {
        $plates = "";
    }
    if ($pdfproof === 'yes') {
        $pdfproof = 'PDF Proof @ R25.00';
    } else {
        $hires = '';
    }
    if ($hires === 'yes') {
        $hires = 'HiRes PDF @ R50.00';
    } else {
        $hires = '';
    }
    if ($hardcopy === 'yes') {
        $hardcopy = 'HardCopy Proof @ R150.00';
    } else {
        $hardcopy = '';
    }
    return Response::json([
        'pdf' => $pdfproof,
        'hires' => $hires,
        'hardcopy' => $hardcopy,
        'plates' => $plates
    ]);
}

This is saving the data in my database like this:

HTTP/1.0 200 OK
Cache-Control: no-cache
Content-Type:  application/json
Date:          Thu, 02 Nov 2017 08:26:11 GMT

{"pdf":"PDF Proof @ R25.00","hires":"HiRes PDF @ R50.00","hardcopy":"HardCopy Proof @ R150.00","plates":""}

Then on the front end I am using the twig function {%for%} and it looks like this:

{% set items = __SELF__.items %}
      {% for item in items %}
      <td>{{ item.pdf }}</br>{{ item.hires }}</br>{{ item.hardcopy }}</br>{{ item.plates }}</br></td>
      {% endfor %}

But this does not return anything on the front end.

This feels like I am doing it all wrong as I am a noob with backend dev :P Any help with be greatly appreciated

Ad

Answer

I guess you don't need to convert it to JSON as you not need to work with Javascript

so simply replace your code

return Response::json([
    'pdf' => $pdfproof,
    'hires' => $hires,
    'hardcopy' => $hardcopy,
    'plates' => $plates
]);

with this :

return [
    [
        'pdf' => $pdfproof,
        'hires' => $hires,
        'hardcopy' => $hardcopy,
        'plates' => $plates
    ]
];

as in template you are looping through items so you need to send it an array. its all php code so no need for json.

we return master array(items) which do have its items and when we loop through master array we get its items each time(item)

if you need any further help please comment.

Ad
source: stackoverflow.com
Ad