Can I set the default order in the Table class on cakephp3

In CakePHP 2.x, the models had the $order property. Therefore, I used this property to order my data worldwide. For example, assuming that I need to show a select box with countries in a view in my Country model used to add a row:

 $order = 'Country.country DESC'; 

and then, when I brought the countries from any controller, the data ordered by the name of the country, and not by id or any other field. This was very useful for boxes of choice. On CakePHP 3.x, I cannot find any similar link in the documentation.

Is there anything I can do to sort the data all over the world when I retrieve it, and not use the order option in every find?

+6
source share
5 answers

Just add your favorite property back and use the beforeFind () callback in the Table object to add the value from the property to the query.

Or just create a custom search :

 public function findOrdered(Query $query, $options) { return $query->order([ $this->alias() . '.name' => 'ASC' ]); } 

And use it

 $this->find('list')->find('ordered')->all(); 

Or create an ordered list that returns the entire ordered list.

 public function findOrderedList(Query $query, $options) { return $this->findList($query, $options) ->order([ $this->alias() . '.name' => 'ASC' ]); } 

Or, overload the findList () method directly and call the parent.

Or, if your find() gets called through a relation, you can set the default order for the relations using the sort option.

 $this->hasMany('AuditLogs', [ 'sort' => [ 'AuditLogs.timestamp' => 'desc', ], ]); 
+3
source

You can override the findAll method in your table class.

 public function findAll(Query $query, array $options) { return $query->order(['Country.country' => 'DESC']); } 
+4
source

CakePHP3.x:

If you want to sort the data in your model for each query associated with this model, you can simply sort the query in the model file via beforeFind:

 public function beforeFind(Event $event, Query $query, $options, $primary) { $query->order(['Model.field' => 'ASC']); return $query; } 
+3
source

In CakePHP 3.x, if you want to set the default order for each model request in this way, you can put the following code in your table:

 public function beforeFind ($event, $query, $options, $primary) { $order = $query->clause('order'); if ($order === null || !count($order)) { $query->order( [$this->alias() . '.sort_field_name' => 'sort_order'] ); } } 

If any order set externally, it skips the default order. Otherwise, it will always be sorted by sort_field_name according to sort_order .

+3
source

According to the official docs, see the cakephp book , you can add a public variable to the controller object to set the default sort order

 class InvoicesController extends AppController { public $paginate = [ 'order' => [ 'Invoices.id' => 'desc' ] ]; .... 
+1
source

All Articles