Shayllis Alves de Sousa Shayllis Alves de Sousa - 15 days ago 8
PHP Question

Hidden fields are still listed from database in cakephp 3

I am getting the records from my database in two different points, using "get" and "find" methods. The problem is that when I am using "get", "first" or "last" the hidden fields aren't displayed (Its ok), but when I am using "find" they are still there.

<?php
//My Plugin in /plugins/Comunica/Files/src/Model/Entity/File.php
namespace Comunica\Files\Model\Entity;

use Cake\ORM\Entity;

class File extends Entity
{
protected $_hidden = ['password'];
protected $_virtual = ['protected'];

protected function _getProtected(){
return empty($this->_properties['protected']) ? false : true;
}
}


The Call Method:

<?php
$this->Files->find()->toArray();


Again. It is right when calling just one record (first, last, call), It's just wrong when trying with method "find". Any one knows how to solve this?

Answer

I have found an answer for this problem. The find returns an object that owns the entities of every result, so that you can convert them by using the "findAll" method inside the table's class.

<?php
//My Plugin in /plugins/Comunica/Files/src/Model/Entity/File.php
namespace Comunica\Files\Model\Entity;

use Cake\ORM\Entity;
use Cake\ORM\Query;//Include this class to manipulate the results

class File extends Entity
{
  protected $_hidden = ['password'];
  protected $_virtual = ['protected'];

  protected function _getProtected(){
    return empty($this->_properties['protected']) ? false : true;
  }

 //New formatation code
  public function findAll(Query $query, array $options)
  {
    return $query->formatResults(function ($results) {
      return $results->map(function($row) {
          $row['upload_date'] = $this->dateTimeConvert($row['upload_date']);
          return $row->toArray();
      });
    });
  }
}