Yii2 multiple model search in gridview - php

I had 2 model 'User' and 'UserProfile', I have displayed the data on the list page. I want to do filter for fields 'name_company' ... of model 'UserProfile' but I have no experience. Help me, thank all.
My Index:
<?php
$gridColumns = [
['class' => 'kartik\grid\CheckboxColumn'],
[
'attribute' => 'username',
'value' => function($model){
return Helper::checkRoute('update') ? Html::a($model->username, ['update', 'id' => $model->id]) : $model->username;
},
'format'=>'raw',
'contentOptions' => [ 'style' => 'width: 10%;' ],
],
...
[
'label' => 'Name_company',
'value' => function($model){
$query = $model->userProfile->name_company;
return $query;
},
'contentOptions' => [ 'style' => 'width: 15%;' ],
],
...
],
];
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'options' => [ 'style' => 'table-layout:fixed;' ],
'columns' => $gridColumns,
]);
?>
My index
My Controller:
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->searchContractorUser(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
My model Search, I had model search 'User':
public function searchContractorUser($params)
{
$query = User::find()->join('LEFT JOIN','rbac_auth_assignment','rbac_auth_assignment.user_id = id')
->where(['rbac_auth_assignment.item_name' => 'user-contractor']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'status' => $this->status,
]);
$query->andFilterWhere(['like', 'username', $this->username])
->andFilterWhere(['like', 'auth_key', $this->auth_key])
->andFilterWhere(['like', 'password_hash', $this->password_hash])
->andFilterWhere(['like', 'email', $this->email]);
return $dataProvider;
}

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 display gridview row to particular view?

This is my grid :
I made a query and created a dataprovider to view in a gridview, and now I want to view each row in a particular view. How do I get all line data to send when clicking preview?
on my controller
$model = new Aviso();
if ($model->load(Yii::$app->request->post())) {
$seg = $model->seguradora;
$seguradora = SeguradoraSearch::getNomeSeg($seg);
$query = new Query;
$query->select(['apolice_idapolice','nome','email', 'contacto','premio','data_final','situacao'])
->from('seguro')
->innerJoin('cliente', 'cliente_idcliente = idcliente')
->where(['between','data_final' ,$model->data_inicio,$model->data_final])
->andWhere(['situacao'=> "Pendente"])
->andWhere(['seguradora_idseguradora'=>$seg]);
$dataAviso = new ActiveDataProvider([
'query' => $query,
]);
return $this->render('index',[
'dataProvider' => $dataAviso,'segName'=>$seguradora,
]);
}
return $this->render('create', [
'model' => $model,
]);
}
On My index
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['attribute'=>'nome',
'label'=> 'Cliente',
],
['attribute'=>'email',
'label'=> 'E-mail',
],
['attribute'=>'apolice_idapolice',
'label'=> 'Apolice',
],
'contacto',
['attribute'=>'premio',
'format' => ['decimal', 2],
'label'=> 'Valor (Mts)',
],
'data_final',
['attribute'=>'situacao',
'label'=> 'Situação',
],
['class' => 'yii\grid\ActionColumn', 'template' => '{view}','header' => 'visualizar' ],
],
]); ?>
<?php Pjax::end(); ?>
I wamt to click on the icon visualizar and render on particular view.
You could configure the ActionColumn in proper way using template and urlCreator
assuming $model->id is you target id for the view
['class' => 'yii\grid\ActionColumn',
'template' => '{view}',
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'view') {
return \yii\helpers\Url::to(['your-controller/your-action', 'id' => $model->id]);
}
}
],

Yii2: display some records at the top of GridView widget

In Yii2 app I have model Document which can belong to user. Belonging is set with owner_id field.
In view I display list of Documents using GridView widget. Default sort is by document_id.
Every user sees all documents (event if specific document doesn't belong to him).
But I need to display documents which belongs to current logged in user at the top of GridView. How can I do this?
I suppose I should make some changes to Document::search() method by can't find out what excactly I should do.
Here is my controller action:
public function actionIndex()
{
$modelFullName = $this->modelFullName;
$model = new $modelFullName();
$dataProvider = $model->search(Yii::$app->request->queryParams);
return $this->render(
'index',
[
'model' => $model,
'dataProvider' => $dataProvider,
]
);
}
Part of view:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'columns' => [
[
'attribute' => 'document_id',
],
[
'attribute' => 'status',
'format' => 'raw',
'value' => function($model) {
return $model->statusString;
},
],
[
'attribute' => 'title',
],
[
'attribute' => 'date_created'
],
[
'attribute' => 'client_id',
'value' => function($model) {
return $model->client ? $model->client->title : '';
},
'filter' => ArrayHelper::map(Clients::find()->all(), 'client_id', 'title')
],
[
'attribute' => 'project_id',
'value' => function($model) {
return $model->project ? $model->project->title : '';
},
'filter' => ArrayHelper::map(Projects::find()->all(), 'project_id', 'title')
],
[
'class' => yii\grid\ActionColumn::className(),
'template' => '{view} {delete}',
'buttons' => [
'view' => function ($url, $model) {
return $this->context->getBtn('view', $model);
},
'delete' => function ($url, $model) {
if (Yii::$app->user->can('deletePrsSum')) {
return $this->context->getBtn('delete', $model);
}
},
],
'visibleButtons' => [
'update' => Yii::$app->user->can('updateDocument'),
'delete' => Yii::$app->user->can('deleteDocument'),
]
],
],
]);
Current Document::search() implementation:
public function search($params)
{
$query = self::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['document_id' => SORT_ASC]
]
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
if ($this->client_id) {
$query->andFilterWhere([
'client_id' => $this->client_id,
]);
}
if ($this->project_id) {
$query->andFilterWhere([
'project_id' => $this->project_id,
]);
}
return $dataProvider;
}
UPDATE
So how I managed to do this:
public function search($params)
{
$userId = Yii::$app->user->identity->user_id;
$query = self::find()->select(
"*, IF(owner_id={$userId},(0),(1)) as sort_order"
)->orderBy([
'sort_order' => SORT_ASC,
'document_id' => SORT_ASC
]);
//further code...
Add a filter in your search function to filter with the id of the logged in person/user:
$query->andFilterWhere(['owner_id' => Yii::$app->user->identity->id]);

How to hide rows on condition from GridView?

$query =Cms::find();
$dataProvider = new ActiveDataProvider([
'query' => $query ,
]);
Hi, I'm trying to hide certain rows whose 'Status_id' is set to 'Inactive' which is done using a custom action button I've created in the Actions column. I figured I might be able to do it if I could add my own query in the $dataprovider but I don't know how to do that too. Please help if it's the right way and if not how to do I do it? Thanks in advance.Here's my widget.
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'Contract_id',
'Status_id',
['header' => 'Actions',
'class' => 'yii\grid\ActionColumn',
'template' => '{new_action}',
'buttons' => [
'new_action' => function ($url) {
return Html::a('<span class="glyphicon glyphicon-fire"></span>', $url, [
'title' => Yii::t('app', 'Burn Contract'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to burn this contract?'),
'data-method' => 'post', 'data-pjax' => '0',
]);
}
], 'urlCreator' => function ($action, $model) {
if ($action === 'new_action') {
$url = Url::to(['cms/burn', 'id' => $model->Contract_id]);
return $url;
}
}
],
],
]);
i think this may work:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'Contract_id',
'Status_id',
['header' => 'Actions',
'class' => 'yii\grid\ActionColumn',
'template' => '{new_action}',
'buttons' => [
'new_action' => function ($url) {
return Html::a('<span class="glyphicon glyphicon-fire"></span>', $url, [
'title' => Yii::t('app', 'Burn Contract'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to burn this contract?'),
'data-method' => 'post', 'data-pjax' => '0',
]);
}
], 'urlCreator' => function ($action, $model) {
if ($action === 'new_action') {
$url = Url::to(['cms/burn', 'id' => $model->Contract_id,'burn'=>true]);
return $url;
}
}
],
],
]);
controller:
$query =Cms::find();
if (\Yii::$app->request->post('burn'))
{
$query->where(['<>','Status_id', 'Inactive']);
}
$dataProvider = new ActiveDataProvider([
'query' => $query
]);

kartik\Select2 as filter input in yii2\grid

I've encountered another dummy problem with my Yii2 project. I've got a standard gridView in my view, defined liek this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'layout' => '{items}{summary}',
'columns' => [
[
'class' => 'yii\grid\SerialColumn',
'contentOptions' => [
'style' => 'vertical-align: middle;'
]
],
[
'attribute' => 'name',
],
[
'attribute' => 'type',
'value' => function($model){
/* #var $model app\models\Object */
return $model->typeNames()[$model->type];
},
'filter' => Select2::widget([
'name' => 'ObjectSearch[type]',
'data' => Object::typeNames(),
'theme' => Select2::THEME_BOOTSTRAP,
'hideSearch' => true,
'options' => [
'placeholder' => 'Wybierz typ obiektu...',
'value' => isset($_GET['ObjectSearch[type]']) ? $_GET['ObjectSearch[type]'] : null
]
]),
],
[
'attribute' => 'countryId',
'value' => 'country.name',
'filter' => Select2::widget([
'name' => 'ObjectSearch[countryId]',
'data' => Country::forWidgets(),
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'placeholder' => 'Wybierz państwo...'
]
]),
],
//other columns
],
]); ?>
I've defined a searchModel class:
class ObjectSearch extends Object
{
public function rules()
{
return [
[['type'], 'integer'],
[['name', 'city', 'countryId'], 'string']
];
}
//some other functions
public function search($params)
{
$query = Object::find()->where(['userId' => Yii::$app->user->id]);
$query->joinWith('country');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['countryId'] = [
'asc' => ['countries.name' => 'ASC'],
'desc' => ['countries.name' => 'DESC']
];
if (!$this->load($params) && $this->validate()) {
return $dataProvider;
}
$query->andFilterWhere(['like', 'objects.name', $this->name])
->andFilterWhere(['like', 'city', $this->city])
->andFilterWhere(['=', 'objects.countryId', $this->countryId])
->andFilterWhere(['=', 'type', $this->type]);
return $dataProvider;
}
}
Sorting and searching works fine - I've got correct results. So what's my problem? For standard columns when I type some text in textInput the value of this input stays in it after search. But when I choose some value in Select2 widget search work, but after search the selected value disappear and I've got just a placeholder.
Thanks for your help,
Kamil
You should simply use initValueText param :
initValueText: string, the text to displayed in Select2 widget for the initial value.
e.g. :
Select2::widget([
'name' => 'ObjectSearch[type]',
'data' => Object::typeNames(),
'initValueText' => $searchModel->type,
// ... other params
])
You could also use it as an InputWidget :
Select2::widget([
'model' => $searchModel,
'attribute' => 'type',
'data' => Object::typeNames(),
// ... other params
])

Categories