2013-11-15 95 views
0

我有一個填充數據庫的下拉列表。它工作得很好,有1個鍵和1個值。但是,我怎麼會得到它與1鍵和2值的工作。這兩個值是名字和姓氏。Yii chtml:listData數據庫中有1個鍵值和2個值

<?php 
    $id = Yii::app()->user->id;  
    $clients = Clients::model()->findAll(array("condition"=>"cId = $id")); 
    $list = CHtml::listData($clients, 'id', 'fname'); 
?> 

<?php echo $form->labelEx($model,'clientId'); ?> 

<?php echo CHtml::dropDownList('clientId', $model, $list, array(
    'empty' => 'Select a client', 
    'class' => 'form-control' 
)); ?> 

<?php echo $form->error($model,'clientId'); ?> 

//needs something like this 
$list = CHtml::listData($clients, 'id', 'fname lname'); 

回答

2

我想你應該定義fullnamevirtual attribute,並用它爲你的下拉列表。

例如:

我假設你有一個模型人包含firstnamelastname。您可以定義一個virtual attribute,如:

class Person extends CActiveRecord { 
    public function getFullName() 
    { 
     return $this->firstname . " " . $this->lastname; 
    } 
    ... 
} 

在視圖中,可以使用了CHtml ::類似的ListData:

echo $form->dropDownList($model, 'personid', 
    CHtml::listData(Person::model()->findAll(), 'id', 'fullname') 
); 

我希望這是對你有用。

+0

完美!正是我需要的 –

0

我用這個簡單的方法來在下拉式中設置屬性/字符串。您甚至可以使用選項組的第三個參數。

echo $form->dropDownListRow($model,'personid', 
CHtml::listData(Person::model()->findAll(
array("select"=>"id,concat(firstname ,' ',lastname) as fullname")), 
'id', 'fullname')); 

模型類

public $fullname; 
相關問題