Populate country dropdown

血红的双手。 提交于 2019-12-13 21:33:55

问题


I have a database table with columns ID , Country.

Inside controller i am getting the countries from model:

    $countries = $countries->find('list',array('fields',array('id','country')));
    $this->set('countries',$countries);

In the ctp file i am trying to get the a the dropdown by setting in option value the id and in the text the country name.

   <?= $this->Form->input('Country of residence',array('type'=>'select','options'=>$countries)); ?>

The dropdown is populated by have value the id and as text the id again. How can i get the 'country' as text instead of id ?


回答1:


For 'list', you cannot provide fields array as it is just for key/value pairs. You are supposed to specify keyField and valueField instead.

$countries = $countries->find('list', ['keyField' => 'id', 'valueField' => 'country']);

Alternatively, you can set the displayField() option in your CountriesTable file to have a default valueField set for you. Default keyField would be the primary key of your table. These options would be set automatically if you bake model for the countries table. And then, you are good to go with just

$countries = $countries->find('list');

And, do not use space in the field name of your form. Go through this doc once




回答2:


In your controller change this

$countries = $this->Country->find('list', array('fields' => array('id','country')));
    $this->set('countries', $countries);

to

$countries = $countries->find('list',array('fields',array('id','country')));
$this->set('countries',$countries);

here i am change $country to Country(Which is Model name for Country )

And change your view ctp file

<?php echo $this->Form->input('country_of_residence',array("options"=>$countries,'type'=>'select'));?>

to

 <?= $this->Form->input('Country of residence',array('type'=>'select','options'=>$countries)); ?>

here i am change field Country of residence to field country_of_residence .

its work perfect for you....

thanks



来源:https://stackoverflow.com/questions/37858904/populate-country-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!