Get model index inside ActiveDataProvider, Yii2 - php

I try to get my model position inside dataProvider.
I have a listview with pager:
Pjax::begin();
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemOptions' => ['class' => 'item'],
'itemView' => 'tree_part',
'pager' => [
'class' => ScrollPager::className(),
'enabledExtensions'=> [ScrollPager::EXTENSION_SPINNER],
'spinnerSrc'=> Yii::$app->request->baseUrl.'/images/spinner.gif',
]
]);
Pjax::end();
I know i can access$model, $widget, $index in my partial view tree_part.php, but I cannot figure out how to get current $model index inside the data.
My dataprovider:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['creation_date'=>SORT_DESC]],
'pagination' => [
'pageSize' => 12,
],
]);
So if thepagesize is 12, $index variable will only show the value of 0-11. What I need is to get "global" index out of the total count of models.
Any advice would be highly appreciated.

Possible solution:
$mindex = $index + ($widget->dataProvider->pagination->pageSize * $widget->dataProvider->pagination->page);
Anyways, looking for better one.

Related

limit Listview in yii2 without pagination

I have a Listview in yii2 to display items, in this case the items are video thumbnails, and i want to display only 5, i tried to limit the query...
$dataProvider = new ActiveDataProvider([
'query' => Video::find()
->select(['video.*', 'COUNT(video_like.video_id) AS countlike'])
->joinWith(['likes'])
->groupBy(['video_like.video_id','video.video_id'])
->limit(5)
->orderBy(['countlike' => SORT_DESC])
]);
but it doesnt work...
my listview is:
<?php echo \yii\widgets\ListView::widget([
'dataProvider' => $dataProvider,
'pager' => [
'class' => \yii\bootstrap4\LinkPager::class,
],
'itemView' => '_video_item',
'layout' => '<div class="d-flex flex-wrap">{items}</div>{pager}',
'itemOptions' => [
'tag' => false,
],
]) ?>
Check this doc.
This should work for you:
$dataProvider = new ActiveDataProvider([
'query' => Video::find()
->select(['video.*', 'COUNT(video_like.video_id) AS countlike'])
->joinWith(['likes'])
->groupBy(['video_like.video_id','video.video_id'])
->orderBy(['countlike' => SORT_DESC]),
'pagination' => [
'pageSize' => 5,
]
]);

How to Add Filter Search Like Grid View In List View Yii2

I Want to Add Filter With List View (Some Thing Like What Is In Grid View) but I Don Not Know How Do That
Filters I Want Are CheckBox And DropDown Options.
Here Is My Action Code In SiteController
<?php
public function actionMobiles(){
$searchModel = new MobileSearch();
//$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = new ActiveDataProvider([
'query' => Mobile::find(),
'pagination' => [
'pageSize' => 1,
],
]);
// get the posts in the current page
//$posts = $dataProvider->getModels();
return $this->render('mobiles', ['dataProvider' => $dataProvider,'searchModel' => $searchModel]);
}
?>
In View File I Have 2 Files :
Here Is mobiles View :
<?php
use yii\widgets\ListView;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\ArrayHelper ;
use app\models\Mobile;
?>
<?= ListView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'itemView' => '_mobiles',
]); ?>
And In _mobiles I Have :
<?php
use yii\widgets\DetailView;
?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
//'id',
'id',
'title',
//'ativo',
],
]) ?>
It Shows Data From DataBase Correctly With It Pagination.
But How To Add Filter To Update List(CheckBox And DropDown List Are Use to Update)??
here is the code for you, you should replace attribute and model name according to yours.
[
'attribute' => 'attribute_name',
'label' => 'Email',
'value' => function($model){
return $model->attribute_name;
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map([Your Model]::find()->asArray()->all(), 'id', 'email'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Email', 'id' => 'grid--search-email']
],
Add this line in your view file,
Just above listview widget
echo $this->render('_search', ['model' => $searchModel]);

Yii2 : 'Trying to get property of non-object' in GridView

I want to ask you about using Grid View in Yii2. In my web, i want to pass parameter from controller to gridview and i use it for GET parameter.
My Controller:
$sql = "SELECT * FROM adikbinaan WHERE adikbinaan.jenjang_id = $jenjang";
$n = count(CariAdikBinaan::findBySql($sql)->all());
$adikbinaan = new SqlDataProvider([
'sql' => $sql,
'totalCount' => $n,
'sort' => [
'attributes' => [
'ADIKBINAAN_NAMALENGKAP',
],
],
'pagination' => [
'pageSize' => 20,
],
]);
$adik = new CariAdikBinaan();
return $this->render('index', [
'dataProvider' => $adikbinaan,
'data' => $adik,
]);
My View
<?= GridView::widget([
'dataProvider' => $dataProvider,
'layout'=>"{pager}\n{items}\n{summary}",
'showFooter'=>true,
'showHeader'=>true,
'showOnEmpty'=>false,
'columns' => [
'ADIKBINAAN_NAMALENGKAP',
'ADIKBINAAN_TEMPATLAHIR',
'ADIKBINAAN_TANGGALLAHIR',
[
'label'=>'Aksi',
'format' => 'raw',
'value'=>function ($data) {
return Html::a(Html::encode("Lihat"),'adikbinaan/view?id='.$data->ADIKBINAAN_ID);
},
],
],
]); ?>
And i get "Trying to get property of non-object" in return Html::a(Html::encode("Lihat"),'adikbinaan/view?id='.$data->ADIKBINAAN_ID);
It looks like Action Column but i don't want to use it.
How do i fix it?
data is an array not an object. From the API page for SQLDataProvider:
SqlDataProvider provides data in terms of arrays, each representing a row of query result.
Therefore your code should read
return Html::a(Html::encode("Lihat"), 'adikbinaan/view?id='.$data['ADIKBINAAN_ID']);

How i do custom Yii2 gridview sort?

How can I sort with a customized gridview header?
Please give the difference between label and header in the Yii2 gridview widget dataprovider.
Here is my code:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'class' => 'yii\grid\DataColumn',
'value' => function ($data) {
return $data->myTitle;
},
'headerOptions' => ['style'=>'text-align:center'],
'header' => 'Page Title',
'label' => 'Title'
],
]); ?>
Do header and label perform the same function?
How can I perform sorting in $data->myTitle?
Here my Output Screen:
I want Page Title, Status, Date Modified should be active.
Thanks in advance.
Found the answer.
Please add attributes to ActiveDataProvider in your Search Model.
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 5,
],
'sort' => ['attributes' => ['myTitle']],
]);
Add the attribute option in widget:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'class' => 'yii\grid\DataColumn',
'value' => function ($data) {
return $data->myTitle;
},
'headerOptions' => ['style'=>'text-align:center'],
'attribute' => 'myTitle',
'label' => 'Page Title'
],
]); ?>
Since myTitle is a field from the database and not a custom value, you can just use attribute. The rest may be unnecessary e.g the default class is DataColumn
'columns' => [
[
'attribute' => 'myTitle',
'label' => 'Label',
]
I am not very sure I understand your question, but sorting option can be included in your modelsearch.php. So in your case you have to do like this.
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['your_column'=>SORT_ASC]]
]);
if myTitle is a field in the database, why you are using such a long syntax. Just
'Columns'=>[
..
'myTitle',
..
],
should work fine and should be active for sorting as you want
if you want a different header/label for the column, use label instead of header as header is only a cell content and cannot be used for sorting, while label can. details
[
..
'attribute'=>'myTitle',
'label' => 'Page Title'
..
],

Yii2 Listview how to display data in view

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

Categories