【问题标题】:Show prename and lastname as select option in CakePHP在 CakePHP 中显示名字和姓氏作为选择选项
【发布时间】:2015-03-25 12:56:10
【问题描述】:

我想用 CakePHP 显示一个表单,用户可以在其中选择员工。 Cake 将输入字段显示为“选择”,这很好。不幸的是,选择输入字段仅显示员工的id,而不是prenamelastname

型号:

提醒:

worker_id (reference to Worker model)

工人:

id
prename
lastname

这里是 PHP 部分:

echo $this->Form->create('Reminder', 
    array('action' => 'add',
        'inputDefaults' => array(
            'label' => false,
            'div' => false
        )
    )
); 

echo $this->Form->input('worker_id', array('empty' => 'Choose an employee'));
echo $this->Form->button('Save', array('type' => 'submit', 'class' => 'btn btn-green')); 

我没有找到显示Worker 类的prenamelastname 的方法,但在选择字段中保留id 作为选项值。

如何做到这一点?

【问题讨论】:

  • 我没有得到您的要求。请举例说明。
  • 我想你要的是选项属性,$this->Form->input('worker_id', array('empty' => 'Choose an employee','options'=>$your_listing ));
  • 嗨,Nilesh,我添加了更多解释。

标签: php forms cakephp select


【解决方案1】:

您需要创建 $your_listing 如下

$your_listing = array('2'=>'John Fleming','3'=>'Justin Bond');

并在您的表单助手中使用此数组,如下所示

echo $this->Form->input('worker_id', array('empty' => 'Choose an employee','options'=>$your_listing)); 

所以在上面的例子中,选择框变成了

<select name="worker_id">
  <option id="">Choose an employee</option>
  <option id="2">John Fleming</option>
  <option id="3">Justin Bond</option>
  </select>

【讨论】:

  • Nilesh,直接从控制器获取$your_listing 数组的最佳方法是什么?如果您可以提供此信息,我将批准它作为答案!谢谢朋友。
  • $your_listing = $this->Article->find('list', array('conditions' => array('Article.status' => 'pending'),'fields'=> array('id','fullname') ));
  • 你还需要在模型中添加这个... public $virtualFields = array( 'fullname' => 'CONCAT(User.first_name, " ", User.last_name)' );
  • @NileshDharmik Snippets 用于可运行的 JS/HTML/CSS 内容,其他任何内容请使用普通代码块。
  • 真棒@NileshDharmik,效果很好!非常感谢!
【解决方案2】:

您可以使用数组来指定选择输入的选项。

$options =  array(
    'Value 1' => 'Label 1',
    'Value 2' => 'Label 2'
)
echo $this->Form->input('worker_id', $options,  array('empty' => 'Choose an employee'));

在你的情况下,你的标签应该是Worker.id =&gt; Worker.prename + Worker.lastname

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2016-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    相关资源
    最近更新 更多