DawnDusk
DawnDusk

Reputation: 69

How do I display the name instead of ID - GridView Yii2

In my _form.php I have created a dependent dropdown for category. After selecting a category and a sub category in my GridView in index.php it displays the ID of the category and subcategor. How do I display the category_name and sub_category name instead of the ID

<?= $form->field($model, 'category_id')->dropDownlist(
                ArrayHelper::map(Category::find()->all(), 'id', 'category_name'),
                [
                    'prompt' => 'Select Category',
                    'onchange' =>'
                    $.post( "index.php?r=sub-cat/lists&id='.'"+$(this).val(), function( data ) {
                    $( "select#tickets-sub_cat_id" ).html( data );
                    });'

                    ]
); ?>

<?= $form->field($model, 'sub_cat_id')->dropDownlist(
                ArrayHelper::map(SubCat::find()->all(), 'id', 'sub_category'),
                [
                    'prompt' => 'Select Sub Category',

                ]
); ?>

GridView code:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'rowOptions' => function($model) {

        if($model->status == 'On Going')
        {
            return ['class' => 'danger'];
        } else if($model->status == 'Done') {

            return ['class' => 'success'];
        } 
    },
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

    //   'id',
         'category_id',
         'sub_cat_id',
    //   'request_title',
        'status',
         [
            'attribute' => 'time_start',
            'value' => 'time_start',
            'filter' => DatePicker::widget([
                'model' => $searchModel, 
                'attribute' => 'time_start',
                'pluginOptions' => [
                    'autoclose' => true,
                    'format' => 'yyyy-m-dd',
                    'todayHighlight' => true
                ]
                ]),
        ],
        'time_end',
        // 'details',
        // 'room_no',
        // 'employee_id',
          'room_no',

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

My model

public function getCategory0()
{
    return $this->hasOne(Category::className(), ['id' => 'category_id']);
}

public function getSubCat()
{
    return $this->hasOne(SubCat::className(), ['id' => 'sub_cat_id']);
}

Upvotes: 0

Views: 919

Answers (1)

Patrick
Patrick

Reputation: 1338

Assuming that your model has the proper relations (e.g. "getCategory"), you can define a grid column as

'category.category_name'

Upvotes: 2

Related Questions