I am referring to this documentation: https://crud.readthedocs.io/en/latest/actions/index.html#findmethod
Is there a way to place the find method in the controller, instead in App\Model\Table
?
What I want to achieve:
I want to apply a filter in the index
action, depending on some conditions. This means for example, that the pagination for Users
should show only users whose name begins with a specific letter and this letter will be provided when the page is refreshed and will always change.
If it's not possible, is there a way I can apply this filter before any data is loaded from the database?
I tried this code in UsersController.php
, but the table shows always all rows. I apparently don't understand how it works.
public function index()
{
$users = $this->paginate($this->Users->find()->where(["id" => 1] ));
$this->set(compact("users"));
return $this->Crud->execute();
}
But, when - for testing - I use an unknown field in the where
condition [for example bar
] then I get this - correct - error message:
Column not found: 1054 Unknown column 'bar' in 'where clause'
So, apparently, the where condition is applied but for some reasons all rows are returned instead of only 1 row with id = 1
. What am I missing?
UPDATE:
After having a look into the source code I see that the string find
is set as prefix for the finder method name, so any other scope is not possible. Maybe in an update this could be considered.
So, now I have these 2 possibilites:
Controller
, but this I still didn't figure out how it works. Even I set it in beforePagination
in the $event
using setData( "query", $this->Users->find()->where( ["id" => 1])
this gets ignored.Solution for question #2:
In UsersController.php
in the index()
method add this:
$this->Crud->on('beforePaginate', function(\Cake\Event\EventInterface $event) {
$this->paginate ['conditions']['id'] = <the-id>;
});