Hello all,
I wanted to get the firstName and Surname to be returned as one string, like this:
'firstName' . ' ' . 'surname'
I tried to do that in the following code but it errored. How can this be done?
'data' => ArrayHelper::map(Guardian::find()->all(),'id','firstName', 'surname'),
Thank you in advance!
flarpy
(Peter)
March 12, 2015, 5:09pm
2
something like
$query = Customer::find()->select(['*', 'name' => 'CONCAT_WS(' ',first_name, last_name)']);
Hang on actually, is that solution active record? This might be used in several databse engines, mysql… Mssql… Ect so want to make sure it’s compatible.
flarpy
(Peter)
March 12, 2015, 8:01pm
5
that is mysql specific, if you need something generic I would recommend you do something in activerecord::afterFind() to concatenate them in php
FYI
'data' => ArrayHelper::map(Guardian::find()->all(),'id', function($array, $default){return $array['firstName'] . ' '. $array['surname'];}),
Vojtech
(Vojtech Horak)
March 12, 2015, 11:38pm
7
You can define the full name in you Guardian ActiveRecord model:
public function getFullName()
{
return $this->first_name . ' ' . $this->first_name;
}
Then it will be accessible as a property ($model->fullName).
And you can create the list like this:
'data' => ArrayHelper::map(Guardian::find()->all('id', 'fullName');
Vojtech
(Vojtech Horak)
March 12, 2015, 11:49pm
8
And by the way, when discussing this topic, I’d just add that I prefer putting the transformation logic to the model. Here is some example of my approach:
Model:
public function getClientPersonList()
{
return ArrayHelper::map(Person::findAll(['person_type_id' => PersonType::TYPE_CLIENT]), 'id', 'clientNameAndID');
}
View (widget):
<?=
$form->field($model, 'client_person_id')->widget(Select2::classname(), [
'data' => $model->clientPersonList,
'options' => [
'placeholder' => Yii::t('app', 'Select {label}...', [
'label' => $model->getAttributeLabel('client_person_id')
]),
],
]);
?>
Sorry missed this reply, that’s a very good idea!
Thank you again Vojtech!