Felicia Limantara
Felicia Limantara

Reputation: 43

Concat 2 columns using listdata in yii

i want to make a dropdown which can show concat of 2 coloumns

here is my code:

  $list = CHtml::listData(Coa::model()->findAllBySql("SELECT id, concat(name,' - ',saldo) as info FROM coa where id_type = 1"),'id','info');
  echo CHtml::dropDownList('id_coa','id', $list, array('prompt'=>'choose account','class'=>'form-control'));

and the table is consist of id, id_type, name and saldo.

i want to concat name and saldo, and then put it in the dropdown options

i've try the code inside the findAllBySql, and it works nicely when i put it on yii, it doesn't work.

Upvotes: 2

Views: 1704

Answers (2)

Vin.AI
Vin.AI

Reputation: 2437

Create a getter function in model class which will return the value of both field in a single string, like this:

class Coa extends CActiveRecord {
    // ...
    public function getNamesaldo() {
        return sprintf('%s %s', $this->name, $this->saldo);
    }
    // ...
}

Then fetch records as normal without use of any concat function, but both fields should be in select query. So, model function can return values of both in one string:

$model_data = Coa::model()->findAllBySql(
    "SELECT id, name, saldo FROM coa where id_type = 1");

Now, here call listData and specify the model property id and getter name, as:

$list = CHtml::listData($model_data, 'id', 'namesaldo');
echo CHtml::dropDownList('id_coa', 'id', $list, array(
    'prompt' => 'choose account', 'class' => 'form-control'));

That's all :)

Upvotes: 4

Rohit Gaikwad
Rohit Gaikwad

Reputation: 815

change

echo CHtml::dropDownList('id_coa','id', $list, array('prompt'=>'choose account','class'=>'form-control'));

to

echo CHtml::dropDownList('id_coa','id', $list, array('prompt'=>'choose account','class'=>'form-control'));

because in CHtml::dropdownlist 2nd argument is default selected value. You cannot specify column name.

Upvotes: 0

Related Questions