Bloodhound
Bloodhound

Reputation: 2966

How to concatenate two columns into an autocomplete field in yii2?

i have a auto complete field in my view whose code is as follows

<?php
            $data = Members::find()
            ->select(['first_name as value', 'first_name as  label','id as id'])
            ->asArray()
            ->all();

            echo 'Name' .'<br>';
            echo AutoComplete::widget([
                 'name' => 'member_name',    
                 'clientOptions' => [
                    'source' => $data,
                    'minLength'=>'3', 
                    'autoFill'=>true,
                    'select' => new JsExpression("function( event, ui ) {
                    $('#receipt-member_id').val(ui.item.id);//#receipt-member_id is the id of hiddenInput.
                 }")],
                 ]);
            ?>

auto complete works correctly, it shows the first name of all the 'members'. But there can be many guys with similar first name, so what i want is to concatenate first_name and last_name. In normal dropdowns it can be done as follows

<?php
    $models1 = Members::find()->all();
    $data = array();
    foreach ($models1 as $model1)
        $data[$model1->id] = $model1->first_name . ' '. $model1->last_name;

    echo $form->field($model, 'member_id')->dropDownList(
                                $data,
                                ['prompt'=>'Select...']);
?>

how can i do this with the autocomplete widget?

Upvotes: 0

Views: 12982

Answers (2)

Hamze Qaempanah
Hamze Qaempanah

Reputation: 71

If you need space between 2 fields, use this:

$data = Members::find()
    ->select(['concat(first_name, SPACE(1), last_name) as name', 'first_name as  label','id as id'])
    ->asArray()
    ->all();

SPACE() method will generate space accord the specific number you entered, for you :D

Upvotes: 3

ScaisEdge
ScaisEdge

Reputation: 133360

try this way

     $data = Members::find()
        ->select(['concat(first_name,last_name) as value', 'first_name as  label','id as id'])
        ->asArray()
        ->all();

Upvotes: 6

Related Questions