Shawn Sonnier
Shawn Sonnier

Reputation: 533

Yii chtml:listData from database with 1 key and 2 values

I have a dropdownlist populated with the database. It works just fine with 1 key and 1 value. But how would i get it to work with 1 key and 2 values. The 2 values are first name and last name.

<?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');

Upvotes: 1

Views: 9367

Answers (2)

Pontus Carme
Pontus Carme

Reputation: 176

I used this easy way to con-cat attributes/strings in drop-down. You can even user third parameter for option group.

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

in model Class

public $fullname;

Upvotes: 1

secretlm
secretlm

Reputation: 2361

I think you should define fullname as a virtual attribute and use it for your dropdownlist.

For example:

I suppose you have a model Person contain firstname and lastname. You can define a virtual attribute like:

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

In a view, you can use CHtml::listData like:

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

I hope it's useful for you.

Upvotes: 3

Related Questions