In Yii framework how can I Combine columns and show as display string in dropdownlist

arun picture arun · Oct 10, 2012 · Viewed 11.3k times · Source

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.

in model

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

in view

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

Answer

dInGd0nG picture dInGd0nG · Oct 10, 2012

Heres another method In model

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

and

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

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.