Yii2 Gridview concatenate two columns

I have a gridview in Yii2 with two columns, first_name and last_name. I want to concatenate these two values ​​into one column named full_name made like tihs: 'name'. ' '.'Surname', the ability to search and filter. How can i do this?

+3


source to share


4 answers


try like this:



<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
         [
            'attribute' => 'an_attributeid',
            'label' => 'yourLabel',
            'value' => function($model) { return $model->first_name  . " " . $model->last_name ;},
        ],

        ['class' => 'yii\grid\ActionColumn',  ],
    ],


]); ?>

      

+9


source


Thanks to this tutorial: Yii 2.0: Filter and Sort by Calculated / Linked Fields in Yii 2.0 GridView

The tutorial only works when searching first_name

and last_name

separately, I added an additional condition filter

to search for the full name in search model

.i.e.

'OR CONCAT(first_name, " ", last_name) LIKE "%' . $this->fullName . '%"'

      

STEP 1: Add a getter function to your base Person model:

Basic installation model

/* Getter for person full name */
public function getFullName() {
    return $this->first_name . ' ' . $this->last_name;
}

/* Your model attribute labels */
public function attributeLabels() {
    return [
        /* Your other attribute labels */
        'fullName' => Yii::t('app', 'Full Name')
    ];
}

      



STEP 2: Add fullName attribute to your PersonSearch model and set up your rules.

Setup search model 
/* your calculated attribute */
public $fullName;

/* setup rules */
public function rules() {
   return [
    /* your other rules */
    [['fullName'], 'safe']
   ];
}

/**
 * setup search function for filtering and sorting 
 * based on fullName field
 */
public function search($params) {
    $query = Person::find();
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    /**
     * Setup your sorting attributes
     * Note: This is setup before the $this->load($params) 
     * statement below
     */
    $dataProvider->setSort([
        'attributes' => [
            'id',
            'fullName' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'label' => 'Full Name',
                'default' => SORT_ASC
            ],
            'country_id'
        ]
    ]);

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $this->addCondition($query, 'id');
    $this->addCondition($query, 'first_name', true);
    $this->addCondition($query, 'last_name', true);
    $this->addCondition($query, 'country_id');

    /* Setup your custom filtering criteria */

    // filter by person full name
    $query->andWhere('first_name LIKE "%' . $this->fullName . '%" ' . //This will filter when only first name is searched.
        'OR last_name LIKE "%' . $this->fullName . '%" '. //This will filter when only last name is searched.
        'OR CONCAT(first_name, " ", last_name) LIKE "%' . $this->fullName . '%"' //This will filter when full name is searched.
    );

    return $dataProvider;
}

      

STEP 3: Set up gridview columns in the view index file

Installation settings file

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        'fullName',
        ['class' => 'yii\grid\ActionColumn'],
    ]
]);

      

+3


source


Gridview graphs are defined by the attributes you listed, which actually translate to yii \ grid \ DataColumn objects. You can specify a custom specific column like this:

'columns=>[
  'first_column',
  'second_column'=>[ //note that using an index like 'second_column' here, is not necessary, but it helps understand what this column definition attempts to define.
    'attribute' => 'first_name', //must be a known model attribute, used for filtering/sorting
    'value' => ($model, $key, $index, $column) { //here you can specify a custom anonymous function to return more complex data for display, note that it WON'T BE HTML ENCODED.
       return $model->first_name  . " " . $model->last_name ;
     }, 
  ],
  'third_column'
]

      

More information on defining custom columns can be found by specifying yii \ grid \ DataColumn Class Reference

+1


source


For filter and sort, the solution is a bit trickier in such a case, when it comes to managing a computed column with fields belonging to the same model, you have to essentially do three things:

  • Adapt the form to be processed in the field calculated (by adding the field and creating the appropriate getter method),
  • Adapt the search model (to filter the query adding andFilterWhere for the computed file).
  • Adjust the view (to handle the new calculated field).

These steps are well described in the following tutorial .

+1


source







All Articles