我正在尝试从表Cities中获取city_name(列)的列表,并将该列表显示在我的下拉列表中
我在控制器方法中编写以下代码
namespace App\Controller;
use App\Controller\AppController;
class PrimeUsersController extends AppController
{
public function initialize()
{
parent::initialize();
$this->viewBuilder()->setlayout('primewishsLayout');
$this->loadModel("Cities");
$this->loadModel("States");
$this->loadModel("Users");
}
public function addnew()
{
// $this->autoRender=false;
$this->set('title',"Add User/Company");
$digits_needed=10;
$random_number=''; // set up a blank string
$count=0;
while ( $count < $digits_needed )
{
$random_digit = mt_rand(0, 9);
$random_number .= $random_digit;
$count++;
}
$this->set("rendomReg",$random_number);
// $view=$this->States->find()->toArray();
// print_r($view);
// city list
$fieds = array('Cities.city_name');
$city = $this->Cities->find()->select(['city_name'])->enableHydration(false)->toList();
// print_r($city);die;
$this->set(compact('city'));
}
}
这是我的下拉列表,我要在其中显示我的商品列表在addnew.ctp
中<div class="col-md-3 pl-1">
<div class="form-group">
<label>City:</label>
<?php
echo $this->Form->control('City',array(
'options' => $city,
'value'=>$option,
'required'=>'required',
'class'=>'form-control',
'label'=>false,
'default' => $option['select']
));
?>
</div>
</div>
我能够提取列表,但是当我单击下拉列表时,列表显示如下:- 1个 坎普尔 2 拉克瑙 3 德里
请帮帮我。
答案 0 :(得分:0)
尝试这样的事情:
$this->Form->select(
'city',
$city,
['required'=>'required',
'class'=>'form-control',
'label'=>false,
'default' => ':Select:']
);
更多说明:https://book.cakephp.org/3.0/en/views/helpers/form.html#common-options-for-specific-controls
答案 1 :(得分:0)
根据Cakephp
CakePHP提供了一种易于使用的方法来生成以下内容的“列表” 数据。从应用程序的数据生成关联数据数组通常很有用。例如,这在创建元素时非常有用。
因此,要获取城市列表,可以在查找查询中使用list
。这将为您提供城市表中ID和城市名称的关联数组。
PrimeUsersController.php
$city = $this->Cities->find('list')->find('list', [
'keyField' => 'id', // specify column name that you used used as city id in cities table
'valueField' => 'city_name' // specify column name that you used used as city name in cities table
])->toArray();
$this->set(compact('city'));
addnew.ctp
$this->Form->select(
'city',
$city,
['required'=>'required',
'class'=>'form-control',
'label'=>false,
'empty' => 'Select City']
);
Cakephp -> Retrieving Data & Results Sets -> Finding Key/Value Pairs
希望这会有所帮助!