du656637962 2016-02-01 11:00
浏览 52
已采纳

Cakephp 3.0如何使用数据库值而不是数字索引填充选择字段

How to populate a select dropdown in cakephp3 from a database table.

Currently Cakephp produces an array (list of options) which is numeric indexed.

The option values should have id of database records (should not be the numeric keys generated by Cakephp)

Departments(table) is a taxonomy to classify events. Events(table) which should store department based list of events.

A event may belongs to many departments. How do I achieve this?

EventsController.php

<?php $department_results = $connection->execute('SELECT departmentname FROM department')->fetchAll('assoc'); // list of departments
$this->set('departmentvalues', $department_results ); 

Events: add.ctp

<?php echo  $this->Form->input('department', array('label' => false,
                                               'div' => false,
                                               'type' => 'select',
                                               'multiple'=>'checkbox',
                                               'legend' => 'false',
                                               'options' => $departmentvalues,
                                               'empty' => 'Please select a Department'
                                                 ));

Objective: A select dropdown with values from database, option values should be id of the database record

Expected result:

<select name="department"><option value="2">Maths</option><option value="4">Physics</option></select>

Issue: cakephp generates numeric indexed array of options.

<select name="department"><option value="0">Maths</option><option value="1">Physics</option></select>

</div>
  • 写回答

2条回答 默认 最新

  • dongxin991209 2016-02-01 18:07
    关注

    You should really use the CakePHP standard for querying your models, instead of raw SQL, especially in the case of a simple list.

    Something like the below should do what you need:

    $department_results = $this->Departments->find('list')
        ->hydrate(false)
        ->fields(['id','departmentname'])
        ->toArray();
    $this->set('departmentvalues', $department_results);
    

    Note that you will need to include the fields as you have named your column departmentname. By default, a find('list') should return id and name fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改