PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, March 3, 2022

[FIXED] how to add relational attributes to gridview yii2?

 March 03, 2022     frameworks, php, web, yii, yii2     No comments   

Issue

i have a new question yii2. how to show relational values from other tables in gridview in views/viewname/index and also add a button to that for confirm?

thank you

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\models\LaptopSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Laptops';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="laptop-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Laptop', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'network',
            'technology',
            'sup_id',
            'speaker',
            // 'optical_drive',
            // 'webcam',
            // 'touchpad',
            // 'card_reader',
            // 'ethernet',
            // 'vga',
            // 'hdmi',
            // 'usb3_ports',
            // 'usb2_ports',
            // 'usb_type_c',
            // 'thunderbolt_ports',
            // 'serial_ports',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>

how to add here new attributes and also add a button?


Solution

for get the related values you can add to your model

a function for the relation

public function getYourRelatedModel()
{
    return $this->hasOne(YourRelatedModel::className(), ['id' => 'your_id_fk']);
}

and the add a getter for the field you need

public function getYour_field() {
    return $this->yourRelatedModel->your_field;
}

and last add to your gridview the column

'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'network',
        'technology',
        'sup_id',
        'speaker',
        'your_field',


Answered By - ScaisEdge
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing