Yii2 : Cannot Show Data in Widget GridView - mysql

I try to show data from database in view using gridview, but i got problem
error message
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: yii\db\ActiveQuery::getCount()
my controller
public function actionIndex()
{
$sql = "SELECT presensi.presensi_tanggal 'tanggal', sum(if( hadir.keteranganhadir_id='1',1,0)) 'hadir', sum(if( hadir.keteranganhadir_id='2',1,0)) 'tidak_hadir', count(*) 'total' FROM hadir, keteranganhadir, presensi where hadir.keteranganhadir_id = keteranganhadir.keteranganhadir_id and hadir.presensi_id = presensi.presensi_id group by presensi.presensi_tanggal";
$model = Hadir::findBySql($sql)->all();
return $this->render('index', [
'hadir' => $model,
]);
}
my view
<?= GridView::widget([
'dataProvider' => $hadir,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'tanggal',
'hadir',
'tidak_hadir',
'total',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How can i fix the problem?

Gridview looks for dataprovider, not array of activerecord models you have sent:
http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html
in your controller/actionIndex
$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM user WHERE status=:status
', [':status' => 1])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM user WHERE status=:status',
'params' => [':status' => 1],
'totalCount' => $count,
'sort' => [
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
],
'pagination' => [
'pageSize' => 20,
],
]);
return $this->render('index', [
'hadir' => $dataProvider,
]);

You can try this:
In Controller.php file:
public function actionIndex()
{
$searchModel = new InvoiceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Your view file seems to be true. Just add above code in your controller file.

Related

Yii2: Add data picker for gridview

I have output code for certain data from related tables. but I also have the task to add 2 search fields by date.
There should be 2 fields created_at and end_at choosing the date in which I would be able to filter out the extra data
my Controller:
{
$dateNowMinusMonth = new \DateTime('-1 month');
$payed = OrderPayment::find()->where(['status' => OrderPayment::STATUS_PAYED])
->andWhere(['>=', 'created_at', $dateNowMinusMonth->format('Y-m-d H:i:s')])
->all();
$orderIds = ArrayHelper::getColumn($payed, 'order_id');
$elements = [];
if ($orders = Order::find()->where(['id' => $orderIds])->all()) {
foreach ($orders as $order) {
foreach ($order->elements as $element) {
$product = $element->product;
if (array_key_exists($product->id, $elements)) {
$elements[$product->id]['count'] += 1;
} else {
$elements[$product->id] = [
'name' => $product->name,
'barcode' => $product->barcode,
'count' => 0,
'amount' => $product->storitem->amount,
'item_cost' => $product->purchase->item_cost,
'price' => $product->price,
];
}
}
}
}
$dataProvider = new ArrayDataProvider([
'allModels' => $elements,
'sort' => [
'defaultOrder' => ['count' => SORT_DESC],
'attributes' => ['name', 'count', 'barcode', 'amount', 'item_cost', 'price']
],
'pagination' => [
'pageSize' => 15,
],
]);
return $this->render('Reporat', [
'dataProvider' => $dataProvider,
]);
}
and view:
<?= GridView::widget([
'id' => 'search-table',
'dataProvider' => $dataProvider,
'striped' => false,
'options' => ['class' => 'text-center'],
'columns' => [
'name',
'barcode',
'item_cost',
'price',
'count',
'amount'
],
]); ?>
Please help me add 2 fields by which I would be able to filter the displayed data by date of creation and end date.

Yii2 foreach loop inside $menuItems

I have a menu like this
<?php
NavBar::begin([
'brandLabel' => Html::img('#web/images/cennos1.png', ['alt'=>Yii::$app->name]),
'brandUrl' => Yii::$app->homeUrl,
'brandOptions' => ['style' => 'margin-top:-7px;'],
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = [
'label' => 'Teams',
'items' => [
foreach ($teams as $team) {
['label' => '' . $team->name .'', 'url' => ['team/preview','id' => $team->id]],
}
],
];
I tried to use foreach loop like that to list all teams as a dropdown menu for guest users to see but it didn't work.
Please help me with this. Sorry for my bad English.
Thank you.
This may not be the best way, but it works for me.
function items($teams)
{
$items = [];
foreach ($teams as $team) {
array_push($items, ['label' => '' . $team->name .'', 'url' => Url::to(['team/preview', 'id' => $team->id])]);
}
return $items;
}
NavBar::begin([
'brandLabel' => Html::img('#web/images/cennos1.png', ['alt'=>Yii::$app->name]),
'brandUrl' => Yii::$app->homeUrl,
'brandOptions' => ['style' => 'margin-top:-7px;'],
'options' => [
'class' => 'navbar-inverse navbar-fixed-top',
],
]);
$menuItems = [];
$menuItems[] = ['label' => 'Login', 'url' => ['/site/login']];
$menuItems[] = [
'label' => 'Teams',
'items' => items($teams)
];
Hope it helps,

Kartik export widget not export search result Yii2

Fighting form last 3 days not able to find what exactly problem is. When after search I export data it export all data, expected to export search result.Please help!
My Controller
public function actionAdvancesearch()
{
$searchModel = new CandidateSearch();
$model = new Candidate();
$dataProvider1 = $searchModel->search(Yii::$app->request->queryParams);
if(Yii::$app->request->post()){
$postedData=Yii::$app->request->post();
$searchModel = new CandidateSearch();
$dataProvider1 = $searchModel->searchAdvanced();
return $this->render('candidateAdvSearch', ['dataProvider1' => $dataProvider1,
'model' => $model ,
'searchModel' => $searchModel,
'posted'=>"posted",
'postedData'=>$postedData]);
}else{
return $this->render('candidateAdvSearch', ['searchModel' => $searchModel, 'model' => $model, 'dataProvider1' => $dataProvider1]);
}
}
View
Pjax::begin();
if($dataProvider1){
$gridColumns = [
[
'attribute'=>'HRMS_candidateID',
'label'=>'Candidate ID',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateID;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateFirstName',
'label'=>'Candidate FirstName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateFirstName;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateLastName',
'label'=>'Candidate LastName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateLastName; },
'format'=>'raw'
],
];
$fullExportMenu = ExportMenu::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'target' => ExportMenu::TARGET_POPUP,
'fontAwesome' => true,
'pjaxContainerId' => 'kv-pjax-container',
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]);
// Generate a bootstrap responsive striped table with row highlighted on hover
echo GridView::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container']],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Candidate Advanced Search</h3>',
],
'toolbar' => [
$fullExportMenu,
],
'striped'=>true,
'hover'=>true,
'responsive'=>true,
'hover'=>true,
'resizableColumns'=>true,
'persistResize'=>false,
'columns' => $gridColumns,
]);
}
Pjax::end();

Yii2 Order by calculated field

I have two tables:
Orders:
- id
- client
- ...
Lines:
- orderID
- startDate
- endDate
- ...
In my orders' Controller I added these two to get dates from each order lines:
public function getStartDate()
{
return OrdersLines::find()
->andWhere(['orderID'=>$this->id])
->min('startDate');
}
public function getEndDate()
{
return OrdersLines::find()
->andWhere(['orderID'=>$this->id])
->max('endDate');
}
In my Index view (using kartik's grid and expandRowColumn) I show the orders grid with 2 calculated columns:
start_Date: gets the sooner start date from lines for each order
end_Date: gets the higher end date from lines for each order
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'export' => false,
'columns' => [
[
'class' => 'kartik\grid\ExpandRowColumn',
'value' => function ($model, $key, $index, $column) {
return GridView::ROW_COLLAPSED;
},
'detail' => function ($model, $key, $index, $column) {
$searchModel = new OrdersLinesSearch();
$searchModel->orderID = $model->id;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return Yii::$app->controller->renderPartial('_ordersLines', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
},
],
...
[
'attribute' => 'start_Date',
'format' => 'date',
'label' => 'Start Date',
'value' => 'startDate',
],
[
'attribute' => 'end_Date',
'format' => 'date',
'label' => 'End Date',
'value' => 'endDate',
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
How can I set OrdersSearch model to allow sorting with these values (start_Date and end_Date)?
I think that you should create ActiveDataProvider using join in ActiveQuery, using sort parameter passed to action:
$sort = \Yii::$app->request->get('sort');
if($sort == 'startDate') $having = 'MAX(startDate)';
if($sort == 'endDate') $having = 'MAX(endDate)';
$sql = Orders::find()->joinWith(['lines' => function($q) use($having) {
$q->having = $having;
}]);

Why is the button page on my gridview not shown?

i have model from "feedbackmodel" :
public function search($params)
{
$query = Feedback::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['TANGGAL'=>SORT_DESC]],
'pagination' => array('pageSize' => 10),
]);
$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->andFilterWhere([
'ID_KOMENTAR' => $this->ID_KOMENTAR,
'id' => $this->id,
'TANGGAL' => $this->TANGGAL,
]);
$query->andFilterWhere(['like', 'KOMENTAR', $this->KOMENTAR]);
return $dataProvider;
}
and the gridview code like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout'=>"{items}",
'tableOptions' => ['class' => 'table table-bordered table-hover'],
'showFooter'=>false,
'showHeader' => false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
'columns' => [
[ 'attribute' => 'iduser.photo',
'format' => 'html',
'value'=> function($data) { return Html::img($data->imageurl) . " <p class='feedback-username'>" . $data->username . "</p>"; },
'contentOptions'=>['style'=>'max-width: 10px; max-height: 10px'],
],
[ 'attribute' => 'KOMENTAR',
'format' => 'raw',
'value' => function($model) { return $model->KOMENTAR ."<br><p class='feedback-date'>". $model->TANGGAL ."</p>";},
],
[ 'class' => 'yii\grid\ActionColumn',
'contentOptions'=>['style'=>'width: 5px;'],
'template' => '{update} {delete}'
],
],
]); ?>
But why the page button is not shown, its limited but i can see the other data bcos the i cant find the button next or prev to the other page
I test your code
if I remove the layout=>"{items}", the page buttons are show otherwise not (i think your layout assignment mean show only the item and not the pager) try simply comment it
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//'layout'=>"{items}",
'tableOptions' => ['class' => 'table table-bordered table-hover'],
'showFooter'=>false,
'showHeader' => false,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
..........