Gibs
Gibs

Reputation: 774

Displaying field of another table in a gridview Yii 2

I have one table named hosts and the other one is hostgroup. On my hosts' table it has these fields: id, name and hostgroup_id. On my hostgroup table its fields are id and name too. I wanted to display on the view/index.php from host table showing its id, name and from hostgroup table hostgroup.name according to its id. Also, do you have any idea how I can make it redirect to theupdatepage ofhostgroup` of that certain id?

In my main_directory/model/HostsSearch.php I have this:

public function getHostgroup()
{
    return $this->hasOne(HostgroupsSearch::className(), ['id' => 'parent_host_id']);
}

While under my main_dir/view/hosts/index.php I have this:

  <?=
  GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'id',
            'name',
            'parent_host_id.name',
            [
                'label' => 'Name',
                'value' => 'HostgroupsSearch.name',
            ],
            'ip_address',
            'object_name',
        ],
    ?>  

Upvotes: 1

Views: 2776

Answers (1)

vishuB
vishuB

Reputation: 4261

Add this function in your main_directory/model/Hosts.php model file

public function getHostgroup()
{
    return $this->hasOne(HostgroupsSearch::className(), ['id' => 'parent_host_id']);
}

Grid View:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        'id',
        'name',
        'parent_host_id.name',
        [
            'label' => 'Name',
            'value' => 'hostgroup.name',
        ],
        'ip_address',
        'object_name',
    ],
?> 

Upvotes: 2

Related Questions