Question

In this instance I'm working with two models: Departments, and Users.

Departments belongsTo Users (In this instance, a user is a department manager [null allowed].)

Using FormHelper, I simply defined the selection of the User id as:

echo $this->Form->input('user_id', array('label'=>'Department/Group Manager (leave blank if none)', 'empty' => true));

By default, FormHelper seems to order the selection items by User.id ASC (the HTML select element's "value" property). To make things nicer in the add.ctp form, I created a virtual field as "Lastname, Firstname" to be used as the User model's display field:

public $virtualFields = array(
  'name' => "CONCAT(User.lastName, ', ', User.firstName)"
);
public $displayField = 'name';

This worked great. Unfortunately, I'd love to be able to order the items in the rendered select box by the virtual field's value, ascending (or User.lastName in this case) instead of by User.id. I was unable to figure out a way to do this using FormHelper. Is there another way to do this (if FormHelper can't do it)?

Was it helpful?

Solution

MVC: The MODEL retrieves the data (business logic).

The CONTROLLER sets the data for the view [$this->set()].

The VIEW simply handles your output, and any logic that is not capable of being handled elsewhere.

Using Cake convention based on how the cake bake output is created, you'd want to set the ORDER BY clause in the call to the model's find() method in your controller, related to the particular view. In this case, your Department's add() method.

public function add(){
    // ... other code ...

    $users = $this->Department->User->find('list', array('order' => array('lastName' => 'asc'));
    $this->set(compact('users'));
}

Be aware that if you are using the Containable Behavior you may need to adjust its settings to achieve the default (most likely working) code example above.

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