I build a custom query to count and sum some of the field and then use gridview to display data.
Here is my query:
$query2 = (new \yii\db\Query())
->select([
'date',
'sum( IF(status = "Passed", 1, 0) ) AS passed',
'sum( IF(status = "Failed", 1, 0) ) AS failed',
'sum( IF(status = "On Hold", 1, 0) ) AS onhold',
'sum( IF(status <> "NULL", 1, 0) ) AS total'
])
->from('qa3d')->where(['week'=>$week])
->groupBy('date');
$dataProvider2 = new ActiveDataProvider([
'query' => $query2,
]);
And my gridview:
<?= GridView::widget([
'dataProvider' => $dataProvider2,
// 'filterModel' => $searchModel,
'headerRowOptions' => ['class' => 'kartik-sheet-style'],
'filterRowOptions' => ['class' => 'kartik-sheet-style'],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => 'Status Report by Analyst - Week to Date',
],
'toolbar' => [
'{toggleData}',
],
'pjax' => true,
'columns' => [
'date',
'passed',
'failed',
[
'attribute' => 'onhold',
'label' => "On Hold",
],
'total',
],
]); ?>
I commented out the filterModel because it's not working. How can I build a search like Gii CRUD generator did for this custom query?
Please help me with this.
Thank you!
Yes you have. You must create search form that point to action of that page then u must decide how will you forward params. You can put it to search model or get it and pass to query you have. IT depends where is your query.
$searchModel = new SomeSearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
or like this and then access array elements.
$post = Yii::$app->request->queryParams;
In your case I supposed you will search for $week = $post['week'];
Related
I have this UrlManager rule:
'<pageSlug>-pa<pageId:\d+>' => 'page/page',
Then I have page with url like this domain.com/blog-pa54
In this example I have
pageSlug = blog and pageId = 54
In my view I have ListView with my blog posts.
I set my dataprovider like this:
$dataProvider = new ActiveDataProvider([
'query' => BlogPost::find()
->where([
'active' => 1
]),
'pagination' => [
'defaultPageSize' => 3,
//'params' => [], when I set this, it only shows get param "page"
'pageParam' => 'page',
'route' => $pageURL, // this variable is equal to "blog-pa54"
],
]);
My route is current url slug - blog-pa54
When I go to next page I recieve this url: blog-pa54?pageSlug=blog&pageId=54&page=2
How can I remove $_GET params pageSlug and pageId from url?
I try to set pagination > params = [] and it remove this get param, but when I go to other page it doesn't change items in my ListView
Here is also my ListView and LinkPager
<div class="blog-post-wrapper">
<?= ListView::widget([
'dataProvider' => $blogPostsDataprovider,
'itemOptions' => ['tag' => null],
'options' => [
'tag' => false,
],
'layout' => "{summary}<div class='row'>{items}</div>",
'itemView' => function ($model, $key, $index, $widget) use ($page) {
return $this->render('//blog-post/_blogPostList', [
'page' => $page,
'model' => $model
]);
},
]); ?>
</div>
<?= \yii\widgets\LinkPager::widget([
'pagination' => $blogPostsDataprovider->pagination,
'linkContainerOptions' => [
'class' => 'page-item',
],
'linkOptions' => [
'class' => 'page-link',
],
]); ?>
Okay, I figured it out.
params attribute must not be empty.
You can set it like this:
'params' => [
'page' => isset($_GET['page']) ? $_GET['page'] : 1,
]
Or if you have another get params like get filters:
$getParams = [];
if(isset($_GET)){
foreach($_GET as $getKey => $getValue){
if(in_array($getKey, ['pageSlug', 'pageId'])){ //here I skip my params from UrlManager rule
continue;
}
$getParams[$getKey] = $getValue;
}
}
.....
'params' => $getParams
I am working on yii2 in my project, I have users and their roles. Each role is given access to a Module and a Sub Menu. There is a sub-menu named SIM List in which all the SIM records can be viewed. There is a field named issued_to which tells us that which SIM has been issued to which user.
Unless a SIM is issued to any user, the issued_to field will remain empty. Once issued the name of the user will appear on the SIM List.
Now I want to manage it in such a way that only a specific user can see the list. For example 5 Sims have been issued to a user named U. Now the user U should only see that SIM records which are issued to him, otherwise the list should be empty.
In my Index controller I am getting issued_to field name which is empty by default.
public function actionIndex()
{
$searchModel = new SimsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
By doing like below I can get issued_to user id
$model = $dataProvider->getModels()[0];
$user_id = $model['issued_to'];
var_dump($user_id);
exit();
Now in this controller, I want to add a check of user_id which gives me only the records which are of that specific user.
Index View
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'imsi',
'sim_number',
'operator_name',
'data_details',
'sms_details',
'monthly_bill',
//'created_by',
[
'label' => 'Created By',
'value' => function ($data) {
if (is_object($data))
return $data->created->name;
return ' - ';
},
//'filter' => Html::activeDropDownList($searchModel, 'created_by', \app\models\User::toArrayList(), ['prompt' => "Created By", 'class' => 'form-control']),
],
'created_at',
// 'updated_at',
'status',
// 'updated_by',
//'sim_stauts',
[
'label'=>'SIM Status',
'value'=>function($a){
return $a->getStatusvalue();
}
],
//'issued_to',
[
'label' => 'Issued To',
'value' => function ($d) {
if(is_object($d->user))
//return $d->user->name;
return $d->issued_to == '' ? '' : $d->user->username;
return ' - ';
// return $d->user->name;
},
'filter' => Html::activeDropDownList($searchModel, 'issued_to', \app\models\User::toArrayList(), ['prompt' => "Users", 'class' => 'form-control']),
],
//'returned_by',
[
'label' => 'Returned By',
'value' => function ($d) {
if(is_object($d->user2))
//return $d->user->name;
return $d->returned_by == '' ? '' : $d->user->username;
return ' - ';
// return $d->user->name;
},
'filter' => Html::activeDropDownList($searchModel, 'returned_by', \app\models\User::toArrayList(), ['prompt' => "Users", 'class' => 'form-control']),
],
'historic',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Update 1
My search model is below
public function search($params)
{
$query = Sims::find();
// add conditions that should always apply here
$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;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'created_by' => $this->created_by,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'updated_by' => $this->updated_by,
'sim_stauts' => $this->sim_stauts,
'issued_to' => $this->issued_to,
'returned_by' => $this->returned_by,
'historic' => $this->historic,
]);
$query->andFilterWhere(['like', 'imsi', $this->imsi])
->andFilterWhere(['like', 'sim_number', $this->sim_number])
->andFilterWhere(['like', 'operator_name', $this->operator_name])
->andFilterWhere(['like', 'data_details', $this->data_details])
->andFilterWhere(['like', 'sms_details', $this->sms_details])
->andFilterWhere(['like', 'monthly_bill', $this->monthly_bill])
->andFilterWhere(['like', 'status', $this->status]);
return $dataProvider;
}
How can I achieve it? Any help would be highly appreciated.
As per your description, you have the user_id saved inside the issued_to field and you need to only fetch the results that have the current logged in user_id saved in the field issued_to.
I assume that your search in the grid view is visible to only logged-in users.
You should set the issued_to param manually by first getting the queryParams array from the request object Yii::$app->request->queryParams; which has the array in the same format as the POST has i.e ['ModelName']['field_name'] so you need to infact set the issued_to as
$arrayParams['SimSearch']['issued_to']=Yii:$app->user->id;
Your actionIndex should look like below
public function actionIndex()
{
$searchModel = new SimsSearch();
$queryParams=Yii::$app->request->queryParams;
//check if user or one of the managers
$isAdmin=in_array(Yii::$app->user->identity->user_role,[1,6]);
//set params if normal user
if(!$isAdmin){
$queryParams['SimsSearch']['issued_to']=Yii::$app->user->id;
}
$dataProvider = $searchModel->search($queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Hope this helps you out.
My controller:
$params = Yii::$app->request->queryParams;
$query4 = (new \yii\db\Query())
->select(['monthsubmit', 'modeler'])
->from('sku3d')
->groupBy(['monthsubmit', 'modeler'])
->orderBy(['monthsubmit'=>SORT_DESC]);
$query4->andFilterWhere(['like', 'monthsubmit', $params['monthsubmit']])
->andFilterWhere(['like', 'modeler', $params['modeler']]);
$dataProvider4 = new ActiveDataProvider([
'query' => $query4,
]);
MY view:
<?php echo GridView::widget([
'dataProvider' => $dataProvider4,
'filterModel' => true,
'pjax'=>true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-user"></i>Submitted SKU by Month</h3>',
],
'columns' => [
// 'monthsubmit',
[
'attribute'=>'monthsubmit',
'filter' => Html::input('string', 'monthsubmit')
'width'=>'310px',
'group'=>true, // enable grouping
],
[
'attribute'=>'modeler',
'width'=>'180px',
'filter' => Html::input('string', 'modeler')
'group'=>true, // enable grouping
],
]
]);
?>
I have created sqlDataProvider in my controller and its working. My problem is when i try to create a filter option since im not using the search model for my gridview, it return error Undefined index: monthsubmit.
Please tell me where I'm wrong.
Thank you.
In your controller, you should do as this
$modeler = Yii::$app->request->get('modeler');
$monthsubmit = Yii::$app->request->get('monthsubmit');
$query4 = (new \yii\db\Query())
->select(['monthsubmit', 'modeler'])
->from('sku3d')
->groupBy(['monthsubmit', 'modeler'])
->orderBy(['monthsubmit'=>SORT_DESC]);
$query4->andFilterWhere(['like', 'monthsubmit', $monthsubmit])
->andFilterWhere(['like', 'modeler', $modeler]);
$dataProvider4 = new ActiveDataProvider([
'query' => $query4,
]);
Using CakePHP 3.5.3
Hi,
The below code works works as it should and displays the result set and orders it by the due_date asc.
public $paginate = [
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
public function index()
{
$session = $this->request->session();
// Declare client id 1
$cidOne = null;
$cidOne = $session->read('Cid.one');
// NOTE* DON'T USE ORDER HERE BECAUSE THE SORTS WILL NOT WORK
$query = $this->Activities->find('all')
->where(['cid_1' => $cidOne])
->andWhere(['status' => 1]);
// Send the query to the view.
$this->set('activities', $this->paginate($query));
}
But when I add sortWhitelist as below the initial page load is not sorted by the due_date and no sort arrow is displayed.
public $paginate = [
'sortWhitelist' => [
'due_date', 'related_to', 'subject', 'post_code', 'type', 'priority'
],
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
Thanks for any help. Z.
There must be consistency between the sortWhitelist array, the order array and the paginator link
so if your field is Activities.due_date your code becomes:
public $paginate = [
'sortWhitelist' => [
'Activities.due_date', 'related_to', 'subject', 'post_code', 'type', 'priority'
],
'limit' => 5,
'order' => [
'Activities.due_date' => 'asc'
]
];
and in your view
<?= $this->Paginator->sort('Activities.due_date', __('Due Date')) ?>
If there is no ambiguity in the fields names you can omit the Model name and simply use due_date as column name
how can one open a link in a new tab. in my case i wanna do it in the following code
if( Yii::$app->session->get('department_id') == 5 )
{
$items[] = ['label' => 'Offer Letter',
'url' => Yii::$app->urlManager->createUrl(['dashboard/print_offer_letter', 'id' => $data->id]),
];
i tried like this but didn't work
$items[] = ['label' => 'Offer Letter', ['title'=>'go','target'=>'_blank'],
'url' => Yii::$app->urlManager->createUrl(['dashboard/print_offer_letter', 'id' => $data->id]),
];
any help would be appreciated.
I think you can use something like below:
$items[] = [
'label' => 'items',
'url' => Yii::$app->urlManager->createUrl(['dashboard/print_offer_letter', 'id' => $data->id]),
'linkOptions' => ['target'=>'_blank']
];