The following code is used to display gridview but it shows "data provider" error.
MODELS:
Subcategory.php:
public function getCountries()
{
return $this->hasOne(Subcategories::className(),['id'=>'catid']);
}
VIEW:
subcategory.php:
i have added this following coding to view the saved data in a grid view.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns'=>[
['class'=>'yii\grid\SerialColumn'],
'id',
'categoryname',
[
'attribute' => subcategory,
'value'=>getCountries.subcatname,
],
['class'=>'yii\grid\ActionColumn'],
],
]); ?>
CONTROLLER
public function actionView2()
{
$dataProvider = new ActiveDataProvider([
'query' => Subcategory::find(),
'pagination' => [
'pageSize' => 20
]
]);
$posts = $dataProvider->getModels();
return $this->render('subcategory' [
'dataProvider' => $dataProvider,
]);
}
I have applied this coding but I get the following error:
PHP Notice – yii\base\ErrorException Undefined variable: dataProvider
Related
I have default forms which were generated by crud. I need to update message column.
My View site/index.php
<div class="notifications-events-index">
<?= Html::encode($this->title) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => false,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'date_at',
'type',
'event_id',
[
'attribute' => 'Message',
'filter' => true,
'format' => 'raw',
'value' => function ($model) {
$form = ActiveForm::begin([
'action' => Yii::$app->urlManager->createUrl(['site/update', 'id' => $model->id])
]);
return $this->render('_msg', [
'model' => $model,
'form' => $form,
]);
},
]
],
]); ?>
<?php ActiveForm::end(); ?>
My updateAction in SiteController
public function actionUpdate($id)
{
$model = $this->findModel($id);
$dataProvider = new ActiveDataProvider([
'query' => NotificationsEvents::find()->orderBy('date_at'),
]);
if ($model->load(Yii::$app->request->post())) {
$model->save(false);
return $this->redirect(['index']);
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
findModel is working. When I save my updating values they are not updating. Any ideas?
Possible Reason to not updating the records:
Check validation , there may be a chance some validation is applying.
Check you attribute available in safe in your model .
Debug Your POST data. There may be a chance your post data is not posted .
If you still not able to solve it please post you model as well .
I have a relation between User and Thesis and my dataProvider just displays user attributes and not thesis'ones in the Gridview. Is there a better way to print join attributes than: ['attribute'] => ['table.attribute']?
model:
public function search($params)
{
$query = Request::find()->joinWith('user')->joinWith('thesis')->where(['thesis.staff'=> Yii::$app->user->identity->id]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
view:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'title',
['attribute' => 'thesis',
'value' => 'thesis.title'],
//'company',
'description:ntext',
'duration',
['attribute' => 'user'
'value' => 'user.id'],
//'requirements',
//'course',
'n_person',
'ref_person',
'is_visible:boolean',
//'created_at',
//'staff',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
controller:
public function actionIndex()
{
$searchModel = new SearchRequest();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
You need to add the relation getters on your model.
On your Thesis model, you need to add something like
public function getUser0 () {
return $this->hasOne(\your\user\model\location\User::className(), ['id' => 'user']);
}
Having this on your model will populate via lazy-load the user relation when you call Thesis::user0, in your case, something like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
/// ---- other attributes
['attribute' => 'user0.name'],
/// ---- other attributes
],
]); ?>
Is better to add your code after $this->load($params);
My example is:
.
.
.
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->joinWith('user');
$query->joinWith('thesis');
$query->andFilterWhere(['thesis.staff'=> Yii::$app->user->identity->id]);
.
.
.
I Have two tables "Personal_data" and "Students", Student has Personal_data.
I used Gii to generate the code for views, controlers and models, and I need to show all "Personal_data" from "Students" in a GridView, but i cant get it.
Code from models/PersonalDataSearch.php
public function search($params)
{
$query = PersonalData::find()->joinWith('Students'])->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'document' => $this->document,
'telephone' => $this->telephone,
'direction' => $this->direction,
'sex' => $this->sex,
]);
$query->andFilterWhere(['like', 'names', $this->names])
->andFilterWhere(['like', 'lastNames', $this->lastNames])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'movile', $this->movile]);
return $dataProvider;
}
Code from controllers/PersonalDataController.php
public function actionIndex()
{
$searchModel = new PersonalDataSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Code from views/personal-data/index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'names',
'lastNames',
'email:email',
'movile',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
This view originally show all rows from Personal_data table from all registered people, but I want just show Personal_Data from Students, I added this line:
$query = PersonalData::find()->joinWith('Students'])->all();
and I have this error:
PHP Fatal Error – yii\base\ErrorException
Call to a member function andFilterWhere() on array
how can i solve this problem?
Remove ->all() from
$query = PersonalData::find()->joinWith('Students'])->all();
Data provider is taking care of fetching the data from DB, you just need to build the query (all() is fetching the data). With just a query you can add filters to it so there will be no error for andFilterWhere()
I have 3 tables and i have made relation to What table by using Field table. i want to show name row from What table in Gridview.but it shows me row of data seperated by comma. i want each data in different column. like sql query result with repeated field.
this is my tbon.php model:
public function getWhat()
{
return $this->hasMany(What::className(), ['idw' => 'idw'])
->viaTable('Field', ['id' => 'id']);
}
public function getField()
{
return $this->hasMany(Field::className(), ['id' => 'id']);
}
and in TbonSearch.php i have added these codes:
public $what;
public $field;
and
[['field','what'],'safe']
and in search method, i have added:
$query = Tbon::find()
->joinWith(['field'])
->joinWith(['what']);
and for sorting:
$dataProvider->sort->attributes['what'] = [
'asc' => ['what.name' => SORT_ASC],
'desc' => ['what.name' => SORT_DESC],
];
and add search filter:
->andFilterWhere(['like', 'what.name', $this->what]);
in index i have added this code and here is the problem, i think:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'label'=>'Name',
'attribute' => 'what',
'value' => function ($data) {
$str = '';
foreach($data->what as $name) {
$str .= $name->name.',';
}
return $str;
},
],
data is like this: a,b,c,d for field of name! but i want ID and a then in next row ID and b and etc.
any help will be appreciated!
I dont know your code and I dont get the meaning, but I can answer in general.
A GridView is used to view Data in a Grid. A row in a GridView represents a dataset and presenting data in the form of a table.
foreach($data->what as $name) {
$str .= $name->name.',';
}
I assume you want to display the Name attribute from the relation what. You can simply achieve this with the tablename.columnname syntax.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'label'=>'Name',
'attribute' => 'what.name',
],
If you want to display the ID column additionally:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'label'=>'Name',
'attribute' => 'what',
'value' => function ($data) {
$str = '';
foreach($data->what as $name) {
$str .= ' ';
$str .= $name->id.'';
$str .= $name->name.',';
}
return $str;
},
],
To be more precise (in Terms of your Problem). We have a datamodel with a junction table like the following simple book database.
Example:
If you want to display the names of the authors on the standard CRUD generated index Gridview, you can do something like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'book_name',
[
'label'=>'Author(s)',
'value' => function ($dataProvider) {
$str = '';
foreach($dataProvider->authors as $name) {
$str .= ' ';
$str .= $name->id.' ';
$str .= $name->author_name.',';
}
return $str;
},
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
with the result:
In addition, you can edit the Detail View to display such an information in an extra Gridview. The result can look like this.
To achieve this you have to:
add a data provider to your controller and pass the provider to the view
add a gridview widget in your view and connect the data provider
add a method to your model which crawls the data
view.php aka the view
use yii\grid\GridView;
// other code
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
[
'attribute' => 'author.author_name',
'header' => 'Author(s)',
],
],
]); ?>
BookController.php aka the controller
public function actionView($id)
{
$dataProvider = Book::getAllAuthors($id);
return $this->render('view', [
'model' => $this->findModel($id),
'dataProvider' => $dataProvider,
]);
}
Book.php aka the model
use \yii\data\ActiveDataProvider;
// other code
public static function getAllAuthors($id) {
$query = BookAuthor::find()->where(['book_id' => $id]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}
Greetings
I want to display data from my Atividades model in Yii2
My AtividadesController has the following code for actionView2
public function actionView2()
{
$query = new Query;
$dataProvider = new ActiveDataProvider([
'query' => $query->from('Atividades'),
'pagination' => [
'pageSize' => 20,
],
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
return $this->render('view2', ['dataProvider' => $dataProvider, 'posts' => $posts]);
}
And in my View 2 i have the following List View that appears with the message showing 4 of 4 items, but doesn't shows the items
<?= ListView::widget([
'dataProvider' => $dataProvider,
]); ?>
In Y1.xx i had a property called 'attributes' for display the model fields
How can i display the model fileds in Yii2 inside this Listview
Many thanks in advance
I have solved it by myself :)
It was not hard
In my View2 Written the following code
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_view2',
]); ?>
And then duplicated an original view file, changed its name to _view2, put it in the same folder, and style it has needed
In my ActividadesController changed the actionView2 code to:
public function actionView2()
{
$dataProvider = new ActiveDataProvider([
'query' => Atividades::find(),
'pagination' => [
'pageSize' => 20,
],
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
return $this->render('view2', ['dataProvider' => $dataProvider]);
}
_View2 code
<?= DetailView::widget([
'model' => $model,
'attributes' => [
//'id',
'atividade',
'descricao:ntext',
//'ativo',
],
]) ?>
SOLVED