Use a field from a linked model as a display field in CakePHP

I have a model that does not contain headers. All interesting information is in a related model.

I already read about virtual fields with which you can combine such fields:

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

But that gives me a simple id and date. I need this id to be a name from another model.

+6
source share
1 answer

It really seems to work for Set::combine() . Your display field should not refer to another model, because it is not always guaranteed that it will be combined. Therefore, if the call did not bring data somewhere, it will cause an error.

Instead, using Set::combine() , you can create an array of key values ​​with whatever you want. Although this is less β€œmagical,” it will result in fewer errors.

For the UserController example, let's say you have an isOne profile and you want the user to select the user using a drop-down list with automatic completion (i.e. using FormHelper) that shows the usernames from their profile. We will use Containable to enter profile data.

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

Then in UserController:

 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 will notice that full_name now in the profile model, as it uses the fields of this model. The compilation method creates an array of type

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

What will be automatically used when using FormHelper to create a drop-down list

 echo $this->Form->input('user_id'); 
+6
source

Source: https://habr.com/ru/post/918346/


All Articles