在 Yii 框架中,如何合并列并在下拉列表中显示为显示字符串

在我看来,我有一个 dropDownList,它是从 clients 表中填充的,该表包含诸如 first_namelast_name 之类的列,id 等,现在我想显示 first_namelast_name 作为显示文本和 id> 作为下拉列表中的值,我已经完成将 id 作为值和 first_name 作为显示文本,但在这里我想合并这些列 (first_namelast_name) 并用作显示文本.

I have a dropDownList in my view, it is populating from clients table, the table contains columns like first_name, last_name,id etc., Now I want to show the first_name and last_name as display text and id as value in drop down list, I'm done with id as value and first_name as display text, but here I want to combine those columns (first_name and last_name) and use as display text.

在模型中

function getClients()
{
    $Clients = Client::model()->findAll();
    $list    = CHtml::listData($Clients , 'client_id', 'first_name');
    return $list;
}

正在查看

echo $form->dropDownList($model,'client_id',$model->getClients());

推荐答案

这是另一种方法在模型中

Heres another method In model

function getFullName()
{
    return $this->first_name.' '.$this->last_name;
}

function getClients()
{
    $Clients = Client::model()->findAll();
    $list    = CHtml::listData($Clients , 'client_id', 'fullName');
    return $list;
}

我认为这是一种可重用的方法,因为您不仅可以在下拉列表中使用 fullName 虚拟属性,还可以在任何需要全名的地方使用.

I think this is kinda reusable method since you can use the fullName virtual attribute not only in dropdownlist but everywhere a full name is needed.

相关文章