Salman Riyaz Salman Riyaz - 4 months ago 44
PHP Question

fetch the data from table and display it the gridview in yii 2.0

I have a controller in that i have wrote a function to get the values from the table. and im passing it to the dataprovider.

public function actionBorrower()
{

$user = User::find()->all();

$dataProvider= new ActiveDataProvider([
'user' => $user,
'pagination' => false,
]);

return $this->render('borrower', [
'dataProvider'=>$dataProvider]);
}


Now in the view file i want to display it in the Grid-view, The table in the database has many users i want to fetch all of them and display it one by one.

<?php

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

$this->title = 'Users';
$this->params['breadcrumbs'][] = $this->title;
?>
<section style="margin-top:60px;display:inline-block;height:640px;width:100%;padding:15px 0 0 15px;" class="wrapper">
<div class="user-role-index">

<h1><?= Html::encode($this->title) ?></h1>

<?= GridView::widget([
'dataProvider' => $dataProvider,

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

'id',
'user_id',
//'role_id',


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

</div>
</section>


I dont no where im going wrong, But some errors are coming up like - Setting unknown property: yii\data\ActiveDataProvider::user

I’m new to yii2, kindly any one help me to solve this.. Thank you.

I want to fetch all data from USER Table where the user_type is "1" in USER_TYPE Table.. Two tables are involved in this. How do i write this query in above??

Answer

You should change your definition activedataprovider to:

$dataProvider= new ActiveDataProvider([
    'query' => User::find(),
    'pagination' => false,
]);

Or if you want to get all user before create dataprovider, you should use ArrayDataProvider

$provider = new ArrayDataProvider([
    'allModels' => User::find()->all(),
    'pagination' => false,
]);

Refer to document: http://www.yiiframework.com/doc-2.0/yii-data-activedataprovider.html and http://www.yiiframework.com/doc-2.0/yii-data-arraydataprovider.html

Goodluck and have fun!

Comments