【Cakephp3】selectboxのListを作る【備忘録】

IT技術系

【課題】
Cakephpでselectboxを作るときに、[id,value]の配列を作りたいですよね。
action名のテーブルを使うなら、そのまま出力されます。でも、調整掛けた値を渡したい時にどうするか、今まではloopでやってたんです。下記みたいな感じで。


//make selectbox list
$customerTable = TableRegistry::get('Customers');
$customerResultSet = $customerTable->find()
				->select(['id', 'customer_name'])
				->where(['delete_flg' => 0]);
$customerList = array();
foreach ($customerResultSet as $tmp){
	$customerList += array($tmp->id => $tmp->customer_name);
}
$this->set('customers_list', $customerList);


分かりやすいけど、見たくないソース…

【回答】
→Hashクラスのconbine関数を使えば良かったのですね。


//make selectbox list
$userTable = TableRegistry::get('Users');
$users = $userTable->find('all', ['Users.id', 'Users.username'])->combine('id', 'username');
$this->set('users', $users);

→結合してるモデルでも大丈夫!


//make selectbox list
$users = $this->Customers->Users->find('all', ['Users.id', 'Users.username'])->combine('id', 'username');