Using Yii2 GridView with array of data - php

I have an array:
$arr = ['ID' => 'A1', 'Description' => 'Item to be sold', ...]
In controller:
$provider = new ArrayDataProvider([
'allModels' => $arr,
//'sort' =>['attributes' => ['ID', 'Description'],],
'pagination' => ['pageSize' => 5]
]);
$this -> render('index', ['provider' => $arr]);
In view (index.php):
GridView::widget([
'dataProvider' => $provider,
]);
And there is no result on page. Where it is wrong?

There are few errors in your code.
1) $arr should have the structure like this:
$arr = [
['ID' => 'A1', 'Description' => 'Item to be sold'],
...
],
2) In the render parameters you passed $arr instead of $provider, should be:
$this->render('index', ['provider' => $provider]);
3) You missed return statement before render:
return $this->render('index', ['provider' => $provider]);
Also I don't recommend using spaces around the arrow.
4) You did not specified any columns in GridView. You can add ID and Description like this:
GridView::widget([
'dataProvider' => $provider,
'columns' => [
'ID',
'Description',
],
]);
5) And finally you are not echoing the GridView to the screen. Should be:
echo GridView::widget([...]);
or
<?= GridView::widget([...]) ?>

Related

Yii2- Select2 button as Grid view filter doesn't filter

I want to use Select2 dr as filter in Yii Grid view, but it doesn't filter at all, only refreshes the page.
I take the data from 2 tables - from accounts I take only user_id, and from credits I take everything else. And every filter works, except And the 'user_id' one.
<?php
echo GridView::widget(
[
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'attribute' => 'wp_id',
'value' => 'accounts.user_id',
'filter' => Select2::widget(
[
'model' => $searchModel,
'attribute' => 'wp_id',
'data' => ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id'),
'options' => ['placeholder' => ' --Filter by user id-- '],
'language' => 'en',
'pluginOptions' => [
'allowClear' => true,
],
]
),
],
],
]
); ?>
Here is the action in the controller.
<?php
public function actionIndex()
{
$searchModel = new CreditsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
} ?>
And this is the search model method
<?php
public function search($params)
{
$query = Credits::find()->with('accounts');
$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;
}
if(!empty($this->user_id)) {
$query->andFilterWhere(['=', 'accounts.user_id', $this->user_id]);
}
// grid filtering conditions
$query->andFilterWhere([
'user_id' => $this->user_id,
'wp_id' => $this->wp_id,
'credits_bought' => $this->credits_bought,
'purchase_date' => $this->purchase_date,
'id' => $this->id,
]);
return $dataProvider;
}
} ?>
Thanks in advance!
Because you are passing the wp_id under the GridView filter and selecting the wp_id from the Accounts model as the value of the select2-dropdown
ArrayHelper::map(Accounts::find()->all(), 'wp_id', 'user_id')
Although it is confusing that you use the gridview column attribute wp_id and use the select2 to filter the user_id for the same column but if you are looking to do that you might need to change the above to
ArrayHelper::map(Accounts::find()->all(), 'user_id', 'wp_id')

How to print 1st reminder, 2nd reminder in Yii2 GridView from model?

Here is my view page view.php
<div class="dataTables_wrapper form-inline dt-bootstrap">
<?= GridView::widget([
'dataProvider' => $dataProvider1,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' =>'Date',
'value' => 'date',
],
[
'label' =>'Reminder',
'value' => function($model){
return Yii::$app->session->get('').' '.$model['type'].' '.'reminder';
}
],
[
'label' =>'To',
'value' => 'recipients',
],
]
]); ?>
</div>
This is controller
$dataProvider1 = new ActiveDataProvider([
'query' => DomainReminders::find()
->where(['domain_id'=>$model['id']])
]);
$totalCount = $dataProvider1->getTotalCount();
return $this->renderAjax('view', [
'totalCount' => $totalCount,
'dataProvider' => $dataProvider,
'dataProvider1' => $dataProvider1,
true,
true
);
This is database with column name 'type' I want print like 1st reminder, 2nd reminder, 3rd reminder in grid view
Now here is my output i want print like 1st, 2nd reminder
You may use Inflector::ordinalize() for this:
[
'label' => 'Reminder',
'value' => function ($model) {
return Inflector::ordinalize($model['type']) . ' reminder';
},
],

Yii2 : Add ID tag to gridview

I've createCommand in controller
$receipts=new receipts();
$query1 = new Query;
$query1 ->select(['price','date','id'])
->from('paymentreceipts')
->join( 'INNER JOIN','patient','patient.patient_id =paymentreceipts.patient_id' )
->where('patient.patient_id=:id', array(':id'=>$id))
->orderby ('paymentreceipts.date');
$command1 = $query1->createCommand();
$dataProvider1 = $command1->queryAll();
$gridViewDataProvider3 = new \yii\data\ArrayDataProvider([
'allModels' => $dataProvider1,
'sort' => [
'attributes' => ['price','reg_date','id'],
],
]);
return $this->render('view', [
'model' => $this->findModel($id),
'gridViewDataProvider2' => $gridViewDataProvider2,
]);
in view.php
<?=
GridView::widget([
'dataProvider' => $gridViewDataProvider2,
// 'pjax'=>true,
'summary'=>'',
'showFooter' => true,
'columns' => [
['label' => 'رقم الخدمة',
'attribute' => 'id',
],
[
// 'label'=>'url',
'format' => 'raw',
'value'=>function ($data) {
return Html::a('$data->date','#',['class' => 'receipts','id'=>'id']);
},
],
]
]) ?>
what i need is : add the id in 'attribute' => 'id' number to the link that i created here ['class' => 'receipts','id'=>'id']);
i used 'id'=> $gridViewDataProvider2->id but it doesn't work !
My English is not good , so maybe my question not be clear .
JOIN statement is the reason why you don't receive "id". Because both of your tables have "id" column and it becomes ambiguous to read it. Change you query like below,
$query1 ->select(['price','date','id as receiptId'])
->from('paymentreceipts')
->join( 'INNER JOIN','patient','patient.patient_id =paymentreceipts.patient_id' )
->where('patient.patient_id=:id', array(':id'=>$id))
->orderby ('paymentreceipts.date');
$command1 = $query1->createCommand();
and then you can make the link like below.
return Html::a('$data->date','#',['class' => 'receipts','id'=>$data->receiptId]);

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']);

Categories