Yii2: Add data picker for gridview - yii2

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.

Related

DatePicker widget filter a datetime field

Friends, how do I get my DatePicker component below (in Yii2 Framewok), filter a field of type datetime? Since in the component I can only specify the date format.
_search.php file:
<?php
echo DatePicker::widget([
'model' => $model,
'attribute' => 'start_date',
'attribute2' => 'end_date',
'language' => 'pt',
'type' => DatePicker::TYPE_RANGE,
'separator' => 'até',
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'autoclose'=>true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd',
]
]);
?>
UPDATE
public function search($params)
{
$query = Report::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'created' => SORT_DESC,
]
],
'pagination' => [
'pageSize' => 100,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'created' => $this->created,
'updated' => $this->updated,
'closed' => $this->closed,
'user_id' => $this->user_id,
'status_id' => $this->status_id,
'location_id' => $this->location_id,
'typeperson_id' => $this->typeperson_id,
'field_cpfcnpj' => $this->field_cpfcnpj,
]);
$query->andFilterWhere(['between', 'created', $this->start_date, $this->end_date]);
$query->andFilterWhere(['between', 'closed', $this->start_closed, $this->end_closed]);
return $dataProvider;
}
If i understand correctly, you want to submit form using the date range which should filter the records using the given range.
Looking at you search() method it looks like you have declared 2 public properties/fields in the search model with the name start_date and end_date which you are using with the DatePicker and you are trying to compare the range with the column created.
You need to do the following in order to filter the records correctly
Make sure for the following
The start_date and end_date are declared inside the safe rules for the ReportSearch model.
You need to use the \yii\db\Expression to convert the date in the column to the desired format, and use the php:date to format the given date ranges i.e start_date and end_date.
Add the following before you return the $dataProvider in the search() method
if ($this->start_date !== null && $this->end_date !== null) {
$query->andFilterWhere(
[
'BETWEEN',
new Expression(
'DATE_FORMAT(created,"%Y/%m/%d")'
),
date("Y/m/d", strtotime($this->start_date)),
date("Y/m/d", strtotime($this->end_date)),
]
);
}
Note: if you have the created column saved as timestamp then you need to wrap the field name in the existing query with FROM_UNIXTIME like below, otherwise if the column is of DATE or DATETIME the above will work.
Column type is of TIMESTAMP
if ($this->start_date !== null && $this->end_date !== null) {
$query->andFilterWhere(
[
'BETWEEN',
new Expression(
'DATE_FORMAT(FROM_UNIXTIME(created),"%Y/%m/%d")'
),
date("Y/m/d", strtotime($this->start_date)),
date("Y/m/d", strtotime($this->end_date)),
]
);
}
Your complete search() method will look like below
public function search($params)
{
$query = Report::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'created' => SORT_DESC,
]
],
'pagination' => [
'pageSize' => 100,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'created' => $this->created,
'updated' => $this->updated,
'closed' => $this->closed,
'user_id' => $this->user_id,
'status_id' => $this->status_id,
'location_id' => $this->location_id,
'typeperson_id' => $this->typeperson_id,
'field_cpfcnpj' => $this->field_cpfcnpj,
]);
if ($this->start_date !== null && $this->end_date !== null) {
$query->andFilterWhere(
[
'BETWEEN',
new Expression(
'DATE_FORMAT(created_at,"%Y/%m/%d")'
),
date("Y/m/d", strtotime($this->start_date)),
date("Y/m/d", strtotime($this->end_date)),
]
);
}
$query->andFilterWhere(['between', 'closed', $this->start_closed, $this->end_closed]);
return $dataProvider;
}

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',
],
..........

Yii2 : Cannot Show Data in Widget GridView

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.