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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度