boosterV
boosterV

Reputation: 119

Phalcon pass object from controller into view

I'm new in phalcon and I wonder what is correct way to pass some data from controller into view from database. For example

$lastOrder = LeaOrder::findFirst([   
    'conditions' => 'user_id = ?1',
    'order' => "id DESC",
    'bind'       => [
        1 => $userID,
    ]
]);


$this->view->setVars([
    'lastOrder'=> $lastOnGoingOrder,
]);

Can I show data for the user from LeaOrder object like {{lastOrder->name}} or should I make toArray() before passing object into view and then {{lastOrder[name]}} or this doesnt matter like I handle this? thank you for all advice,

Upvotes: 0

Views: 933

Answers (1)

Nikolay Mihaylov
Nikolay Mihaylov

Reputation: 3876

You can even use the quick syntax:

$this->view->lastOrder = LeaOrder::findFirst([   
    'conditions' => 'user_id = ?1',
    'order' => "id DESC",
    'bind'       => [
        1 => $userID,
    ]
]);

In the view:

// To access object properties
{{ lastOrder.name }}

// To access array keys
{{ lastOrder['name'] }}

Phalcon ORM returns Model objects, however if you really need an array you can call the ->toArray() method on your object.

I would suggest you reading this section from docs: https://docs.phalconphp.com/en/3.2/volt Filters - section is really useful as well.

UPDATE: Debugging ORM results. When dumping ORM result you see tons of information because of DI (dependency injection) that Phalcon is using. One easy way to debug is call ->toArray() on your model. This way you will only see model properties.

$this->view->order = LeaOrder::findFirstById(82);
print_r($this->view->order->toArray();

But please note: toArray() is converting your object into array, but since you are not assigning it and just doing it inside the print_r for debug purpose, later you will use it as object in your code/template.

UPDATE 2: Handy function for Phalcon debugging

function d($what)
{
    if (is_object($what) AND method_exists($what, 'toArray')) {
        $what = $what->toArray();
    }
    echo '<pre>';
    print_r($what);
    die('</pre>');
}

// Usage:
$this->view->order = LeaOrder::findFirstById(82);
d($this->view->order);

Upvotes: 1

Related Questions