Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a field from a related model as your displayfield in CakePHP

Tags:

cakephp

I have a model that contains no titles whatsoever. All the interesting information is in a related model.

I already read about virtualfields, with which you can combine fields like this:

public $virtualFields = array("full_name"=>"CONCAT(event_id, ' ' ,begin)");
public $displayField = 'full_name';

But that gives me with a simple id and a date. I need that id to be the name from the other model.

like image 559
skerit Avatar asked Jun 18 '12 10:06

skerit


1 Answers

This really sounds like a job for Set::combine(). Your display field shouldn't reference a different model, because it is not always guaranteed to be joined in. So if a call somewhere didn't bring in the data, it would throw an error.

Instead, using Set::combine() you can create a key-value array with whatever you want. While this is less "magical," it will result in less possibilities for errors.

For a UsersController example, let's say you have hasOne Profile and want the user to select a user using an auto-populated dropdown (i.e., using the FormHelper) that shows user's full names from their profile. We'll use Containable to bring in the profile data.

class AppModel extends Model {
  $actsAs = array(
    'Containable'
  );
}

Then in UsersController:

function choose($id = null) {
  // regular view code here
  $users = $this->User->find('all', array(
    'contain' => array(
      'Profile'
    )
  ));
  // create a key-value that the FormHelper recognizes
  $users = Set::combine($users , '{n}.User.id', '{n}.Profile.full_name');
}

You'll notice that full_name is now on the Profile model, as it uses fields from that model. The combine method creates an array like

array(
  1 => 'skerit',
  2 => 'jeremy harris'
);

Which will automatically be used when you use the FormHelper to create a dropdown list

echo $this->Form->input('user_id');
like image 110
jeremyharris Avatar answered Oct 31 '22 13:10

jeremyharris