Yii2- Undefined variable: model - php

I tried my best to solve this , but I can't seem to figure out where the problem is. Here is my code:
In action controller
return $this->render('viewcreated', [
'dataProvider' => $dataProvider,
'model' => $this->findModel($id),
'id' => $model->id
/*'searchModel' => $searchModel*/
]);
View
$this->title = $model->id; // here it gives the error
How can I resolve it ?
Any help would be highly appreciated

remove line 'id' => $model->id , as you have not declared $model anywhere and using its value,so its giving error simple.
enter code here
You can do it as,
$model= $this->findModel($id);
return $this->render('viewcreated', [
'dataProvider' => $dataProvider,
'model' =>$model,
'id' => $model->id
]);

You must retrieve the value for $model outside the render call so the $model object is available for all the index you accessing in render call
$model= $this->findModel($id);
Once you have done all the attribute related to the $model object are available avoiding redeclaration so you can call render this way
return $this->render('viewcreated', [
'dataProvider' => $dataProvider,
'model' =>$model,
]);
the value $model->id in view should be accessible directly by the var $model passed on index 'model'

Related

How to add grand total to the bottom of yii2 grid view

I have a grid view which is like this. The columns are calculated with the help of MySQL query and displayed accordingly.
<?php
$subquery = Adanalytics::find()->
select('id,ad_id,date_event,max(cpc) cpclick,max(cpv) cpview,max(impression) impression,max(view) view,max(clicks) clicks,visitor_ip,publisher_id')->
from('ad_analytics')->
where(['publisher_id' => Yii::$app->user->identity->id ])->
groupBy('ad_id,date_event,visitor_ip');
$query=Adanalytics::find()->
select('ad_id,date_event,sum(cpclick) total_click_cost,sum(cpview) total_view_cost,sum(impression) total_impression,sum(view) total_views,sum(clicks) total_clicks,publisher_id')->
from(['t'=>$subquery])->
groupBy('t.ad_id,t.date_event');
?>
<?= GridView::widget([
'dataProvider'=>new ActiveDataProvider([
'query' => $query,
]),
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'ad_id',
'total_impression',
'total_views',
'total_clicks',
'total_click_cost',
'total_view_cost',
'date_event',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
I want to show a grand total column at the bottom of this grid view.
For example
'grand_total_impression',
'grand_total_views', //This is the sum of all displayed views
'grand_total_clicks',//This is the sum of all displayed clicks
'grand_total_click_cost',//THis is the sum of all displayed cost
'grand_total_view_cost',//This is the sum of all displayed view cost
To do that I have code in my controller which is like this.
public function actionIndex()
{
$searchModel = new Adanalytics2Search();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$grandTotal = [];
foreach ($dataProvider->getModels() as $value) {
// var_dump($value);
// exit();
$grandTotal['total_click_cost'] += $value['total_click_cost'];
$grandTotal['total_view_cost'] += $value['total_view_cost'];
}
//var_dump($dataProvider);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'grandTotal' => $grandTotal,
]);
}
But it is producing the error in at this way.
Undefined index: total_click_cost
Where am I going wrong? Or is there any other way to solve this problem?
I strongly advise you to use katrik gridview. It handles page summary much better and implements a lot of other usages. Alternatively add 'showPageSummary' => true at your gridview to display columns summary.
use kartik\grid\GridView;
// Create a panel layout for your GridView widget
echo GridView::widget([
'dataProvider'=> $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'showPageSummary' => true
]);
Similar question: Yii2: Kartik Gridview sum of a column in footer
This has solved the problem anyway.
This in grid column.
[
'attribute'=>'total_impression',
'pageSummary' => true
],
And in grid view
'showPageSummary' => true,

Yii2 Gridview filtering not working

Can you help me out with implementing filters to GridView in Yii2? Right now, my rendered table does not respond to my actions (search GET params are not added, nothing changes if I enter a query to a filter input). Here's my code:
Controller:
$searchModel = new UserSearch();
$dataprovider = $searchModel->search(\Yii::$app->request->get());
return $this->render('index', [
'dataProvider' => $dataprovider,
'searchModel' => $searchModel
]);
Model (UserSearch.php):
public $fullname;
public function rules()
{
return [
[['fullname'], 'safe'],
];
}
public function search($params) {
$query = StUsers::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if(!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere(['LIKE', 'fullname', $this->fullname]);
return $dataProvider;
}
View:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'id',
'fullname'
],
]);
I have the same problem when filtering in DataView. Perhaps the problem is in the client side.
Check again if your jquery called twice on your page ( browser/source code ).
May be your problem related with this also :
jQuery(...).yiiGridView is not a function
There should be no need for a solution since 4 years have passed. But, problem is in next statement:
if(!($this->load($params) && $this->validate())) {
return $dataProvider;
}
Change it to:
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
possibly issue is jquery.min.js
You should referencing not more than once
Try to see if you have repeated.

Yii2 : Dataprovider append query issue in controller

I have append query in controller using dataprovider object but my last query is not apply after used getKeys() method.
Why without getKeys() method is possible but with getKeys() not possible?
Please view my below code.
$searchModel = new MySearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort = false;
$pKey = $dataProvider->getKeys();
$otherId = MyModel::find()->andWhere(['id' => $pKey])->select('id')->column();
//This query is not apply/append when i used `getKeys()` method
$dataProvider->query->andWhere(['id' => $otherId]);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);

Yii2 : How to pass additional parameters to listview

I read this post and answer give by Songwut K. in this question:
Yii2 ListView and dataprovider
But i want to know that is possible to use second model in _item. Suppose the _item is a post in the forum that retrieves data from the $model but I'd like to use a different model like $comment for me comment on a this post and view the post together with a commentary as one _item. Imagie that item is post on facebook and it display only text, date and user which write this post. But how i can add comment to this from other model? I just want to pass my $comment to _item view.
I was tried add new Commnet in my controller:
public function actionIndex()
{
$model = new NewsForm();
$searchModel = new NewsSearch();
$comment= new UrComment();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->setSort(['defaultOrder' => ['Id'=>SORT_DESC]]);
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->saveNews();
return $this->redirect(['/content/news']);
} else {
return $this->render('index', [
'model' => $model,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'comment' => $comment
]);
}
}
And render this to index. But i can use my $comment only in index how can i pass this to _item? i tried this:
<?php
echo ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
'summary'=>'',
'comment' => $comment
]); ?>
And tried in my _item:
<?= $model->getStatus($model->cnNewsContentType_Id); ?> <br>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($comment, 'Text')->textInput(['maxlength' => true])->label('Treść') ?>
<?php ActiveForm::end(); ?>
But have error:
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\widgets\ListView::comment
In _item i can only use $model. It is possible to pass my $comment to _item view? Pls help me
You should simply use viewParams :
Additional parameters to be passed to $itemView when it is being rendered. This property is used only when $itemView is a string representing a view name.
e.g. :
<?= ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
'viewParams' => ['comment' => $comment],
'summary'=>'',
]); ?>

Yii2 ListView and dataprovider

What data must be sended to dataprovider?
In my controller:
public function actionIndex() {
$searchModel = new UserSearch();
$dataProvider = $searchModel->search( Yii::$app->request->queryParams );
//other stuff and sending array of params to view
in a view:
echo ListView::widget( [
'dataProvider' => $dataProvider,
] );
but i got only id`s:
And if i`m set single view like:
'itemView' => '_single',
how send data to _single.php ?
I mean - need default template for view list items like in GridView:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
'email:email',
'password',
'role',
//....
And then i got perfect grid:
Controller - SiteController.php
<?php
// Yii2 Listview Example : by Songwut Kanchanakosai, Thailand.
use common\models\Members;
use common\models\SearchMembers;
...
public function actionIndex() {
$searchModel = new SearchMembers();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
?>
View (1) - index.php
<?php
use yii\widgets\ListView;
...
echo ListView::widget( [
'dataProvider' => $dataProvider,
'itemView' => '_item',
] ); ?>
View (2) - _item.php
<?php
use yii\helpers\Html;
?>
<?=$model->name;?>
<?=$model->age;?>
<?=$model->mobile;?>
Example Result :
Songwut 36 +668-3949-5153
Prawee 41 +668-7323-2334
Kosol 32 +668-8014-0165
Utehn 39 +668-7874-5643
how send data to _single.php ?
Here is how, use $viewParams
$viewParams public property array $viewParams = []
Additional parameters to be passed to $itemView when it is being
rendered. This property is used only when $itemView is a string
representing a view name.
echo ListView::widget( [
'dataProvider' => $dataProvider,
'viewParams'=>['name'=>'My Name is Stefano'], //acccessed in view as $name with value 'My Name is Stefano'
] );
in official docs http://www.yiiframework.com/doc-2.0/yii-widgets-listview.html#$itemView-detail
$itemView public property
The name of the view for rendering each data item, or a callback (e.g. an anonymous function) for rendering
each data item. If it specifies a view name, the following variables
will be available in the view:
$model: mixed, the data model
$key: mixed, the key value associated with the data item
$index: integer, the zero-based index of the data item in the items array returned by $dataProvider.
$widget: ListView, this widget instance
So your User model data should be available in _single.php as $model->username
So i suppose can use Detail View in _single.php i think:
DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'username',
'email:email',
//....

Categories