Search code examples
phpcakephpcakephp-3.xcakephp-3.2

How to access virtual field in controller instead of model entity in cakephp 3.2


I have implemented virtual filed in model/entity/Order.php .

But i want to access for one page only ,i don't want it to be called for all the functions .So in controller how can i access virtual field so that it will be applicable for only the portion i need.

In cakephp 2x version ,i have made for controller ,but this time in 3X i am unable to make it.

below i have attached some codes

Any suggestion will be appreciated. Thank you .

Model/Entity/Order.php

 protected $_virtual = ['amount'];

    protected function _getAmount() {


            $data = [];
            $data['due'] = $this->_properties['collection']['due_amount'];
            $data['paid'] = $this->_properties['collection']['total_sale_amount'] - $this->_properties['collection']['due_amount'];
            return $data;
        }

Codes in controller

   $Lists = $this->Orders->find('all')->where($condition)->contain(['Collections','Customers'=> ['queryBuilder' => function ($q) {
                               return $q->select(['id','center_name']);
                              }],])->order(['Orders.due_date ASC']);

Solution

  • You have used getter method of entity by declaring function _get*. Your getter method name is _getAmount(), so you can access this by entity object in controller $entity->amount();

    $Lists = $this->Orders->find('all')->where($condition)->contain(['Collections','Customers'=> ['queryBuilder' => function ($q) {
                                   return $q->select(['id','center_name']);
                                  }],])->order(['Orders.due_date ASC']);
    
    // Iteration will execute the query.
    foreach ($Lists as $entity) {
            echo $entity->amount;
    }
    

    Check document about virtual field in CakePHP 3.x

    Also no need of below line in Entity, so remove it, because you are using getter method.

    protected $_virtual = ['amount'];