Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top