Cakephp 3.0 how to populate select field with values ​​instead of id

I was looking for the previous answer, but the ones I found are related to older versions of cakephp

I have two tables: “logs” and “problems”, where there is a relationship of “problems” of BelongsTo “logs”, here is what the problem looks like:

public function initialize(array $config){ $this->belongsTo('Magazines', [ 'foreignKey' => 'id' ]); } 
Magazines Magazines

have two fields: journ.id and journ.name

problems with tables have two fields: issues.id, issues.magazine_id, where issues.magazine_id is the foreign key

to fill the selected input in the problem view with .name log values ​​and save the .magazine_id problems, I installed the controller as follows

 $this->set('magazines', $this->Issue->Magazine->find('list')); 

then I added the following code to the add.cpt problem view

  <?php echo $this->Form->input('name', [ 'type' => 'select', 'multiple' => false, 'options' => $magazines, 'empty' => true]); ?> 

but I get select input with .magazine_id questions as values ​​instead of logs. name

thanks for your help and comments

+9
php cakephp
source share
3 answers

You want to use find('list') , as this returns the primary key and display field: -

 $this->set( 'magazines', $this->Issues->Magazines->find('list') ); 

Then in your form you need the input name to be magazine_id if you want to set the foreign key for the association: -

 echo $this->Form->input( 'magazine_id', [ 'type' => 'select', 'multiple' => false, 'options' => $magazines, 'empty' => true ] ); 

See docs for more details.

Update

If you are having trouble find('list') , it is probably because your displayField model displayField not installed correctly. A cake typically defines a displayField for a model during initialization. If this does not work or you want another field, you can set it manually in the initialize() model method. For example: -.

 class MagazinesTable extends Table { public function initialize(array $config) { $this->displayField('name'); } } 

Change 'name' to the appropriate field.

Alternatively, you can choose which Cake field will use for the values ​​returned by find('list') (this is especially useful if you want to override the default displayField ). For example: -.

 $this->Issues->Magazines->find('list', [ 'keyField' => 'id', 'valueField' => 'name' ]); 
+18
source share

Display the selected option in the assistant of the month

 $this->Form->month('students.month', [ 'label' => false, 'value'=>date('m'), 'required'=>true ]); 
0
source share

It really helped me.

 $this->Issues->Magazines->find('list', [ 'keyField' => 'id', 'valueField' => 'name' ]); 
0
source share

All Articles