CakePHP 2.4.4 Unable to sort/order by virtual field with paginate (Paginator)

烈酒焚心 提交于 2019-12-25 03:59:22

问题


My Virtual Field for Property model, generated in beforeFind(), called 'distance', works. However, I can't sort by it. I currently have this as part of the search form:

echo $this->Form->input('sort', array(
    'options' => Hash::get($predefined, 'sort'), // List of options
));

Which adds sort to the URL, and it works for all normal fields, but not the virtual field distance. Should I have implemented this differently? As far as I'm aware, Virtual Fields should work fine with pagination.

EDIT: In case I've implemented pagination wrong...

I've set defaults:

public $paginate = array(
    'limit' => 25,
    'order' => array(
       'Properties.id' => 'asc'
    )
);

After building $conditions:

$this->Paginator->settings = $this->paginate;
$data = $this->Paginator->paginate('Property', $conditions);
$this->set('properties', $data);

The above works fine changing the order, even by directly editing /sort:fieldname/ in the URL, but not with the virtual field 'distance'. I also tried adding, without success:

$this->paginate['order'] = array($value); //Value is the value for 'sort' named parameter

回答1:


This part of your message:

My Virtual Field for Property model, generated in beforeFind(),

Seems to be the issue.

The virtual field needs to be defined before your call to Paginate() so that the paginator knows to build the "sort" criteria.

The beforeFind() call happens after the pagination call, so your virtual field is not yet defined. Moving the definition of the virtual field right above the the pagination call should fix this.



来源:https://stackoverflow.com/questions/21484145/cakephp-2-4-4-unable-to-sort-order-by-virtual-field-with-paginate-paginator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!