Yii2: Search form not working with Gridview in Pjax - php

There are some questions here, but the problem is in the filters that are in the gridview.
My problem is that I can not integrate an external form with the gridview itself because I do not want to use the search form that is part of the gridview.
Controller
public function actionIndex()
{
$searchModel = new BlogSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Views
index.php
<?= Html::button('Filter', ['data-toggle' => 'modal', 'data-target' => '#filter-modal', 'class' => 'btn btn-primary']) ?>
<?php
Modal::begin([
'header' => '<h3>Search Blog</h3>',
'id' => 'filter-modal'
]);
echo $this->render('_search', ['model' => $searchModel]);
Modal::end();
?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'title',
'content'
]
]); ?>
<?php Pjax::end(); ?>
_search.php
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'content') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
In the "index.php" the gridview is inside the pjax, but the search form is outside, but even if the form was within "Pjax :: begin" it would not work, either.
That is, when I do the search the page is reloaded. I want only gridview updatated.

As far as I understood from the discussion you don't want to use the filter fields inside the GridView and want to use the search form instead to filter the GridView. if that is correct you need to do 2 things for that
1. Move your form inside the pjax block
index.php
<?= Html::button('Filter', ['data-toggle' => 'modal', 'data-target' => '#filter-modal', 'class' => 'btn btn-primary']) ?>
<?php Pjax::begin(['enablePushState'=>false]); ?>
<?php
Modal::begin([
'header' => '<h3>Search Blog</h3>',
'id' => 'filter-modal'
]);
echo $this->render('_search', ['model' => $searchModel]);
Modal::end();
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'title',
'content'
]
]); ?>
<?php Pjax::end(); ?>
2. And the second an most important thing is to include the option of data-pjax inside the form options.
_search.php
<?php $form = ActiveForm::begin([
'action' => ['index'],
'id'=>'my-form',
'method' => 'get',
'options' => [
'data-pjax' => 1
],
]); ?>
<?= $form->field($model, 'title') ?>
<?= $form->field($model, 'content') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
EDIT
You might find problem with the modal overlay staying there and the modal window itself hides, provide your form with an id like id=>"my-form" and add the following inside your _search.php file to bind the beforeSubmit event for ActiveFormJS
$this->registerJs('$("#my-form").on("beforeSubmit", function (e) {
$("#filter-modal").modal("hide");
});', \yii\web\View::POS_READY);

Related

How to use search button for gridview

Sorry for my english!!
I need your help. I wantto make filtering and search by clicking on button. So, first, I enter a name or age, or both, and then click on the button, and table appears with data that has already been filtered.If all fields are empty and the button is not pressed, then the table should not be visible. The table appears only after clicking. (I'm using database)
Here's my fields for filter and button:
<div class="search">
<?php
echo $form->field($data, 'name')->textInput();
echo $form->field($data, 'age')->textInput();
?>
</div>
<?= Html::submitButton('search'); ?>
And my gridview:
<div class="gridview">
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
'age',
]); ?>
</div>
What i need to write in my controller? I don't understand, i really want to get it!!
Thanks everyone for your attention!!
And what about search by click?
To search out of the GridView you should make like this searching form:
<div class="search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($data, 'name') ?>
<?= $form->field($data, 'age') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Hope it helps you get the right direction.
You can get a multidimensional array of search fields in the controller using the method Yii::$app->request->queryParams Or Yii::$app->request->get()
Also to check and not display the table before searching: (or send blank field)
Create your own gridview and search page using the Gii tool (CRUD Generator)
Then add the required codes (for example)
View File
<div class="search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($data, 'name') ?>
<?= $form->field($data, 'age') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php if ($show === true): ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
'age',
],
]); ?>
<?php endif ?>
Controller(Index action)
public function actionIndex()
{
$searchModel = new YourModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
# code...
// Yii::$app->request->queryParams['YourModelSearch'] Or ...
$get_model = current(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
// Check in whichever way you prefer
'show' => (!empty($get_model['name']) or !empty($get_model['age'])) ? true : false,
]);
}
You can also use JQuery.

Yii2 Basic display create from from another model to a view from another model

I create a CRUD called Channel and a CRUD Post, so I want to add create Post form to DetailView of Channel; example when a user view Channel Alpha under the Alpha details he have a form from Post to create a Post inside that Channel
user can view the detail of a Channel and also can add Post to that Channel
something similar to :
in Channel controller
public function actionView($id)
{
$ly_addPost = new Posts();
return $this->render('view', [
'model' => $this->findModel($id),
'addpost' => $ly_addPost,
]);
}
and in channel view I did edit it to :
//Yii2 code
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\Channel */
$this->title = $model->Channel_name;
$this->params['breadcrumbs'][] = ['label' => 'Channels', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="channel-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Channel_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Channel_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<div class="col-md-12">
<?= $this->render ('_form', [
'addpost' => $ly_addPost,
])
?>
<div class="posts-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'Posts_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Posts_text')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Posts_file')->textInput(['maxlength' => true]) ?>
<?php //= $form->field($model, 'Posts_crdate')->textInput() ?>
<?= $form->field($model, 'Channel_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Permissions_id')->textInput() ?>
<?php //= $form->field($model, 'user_id')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
but I get error :
PHP Notice – yii\base\ErrorException
Undefined variable: ly_addPost
Change addpost to ly_addPost show below
public function actionView($id)
{
$ly_addPost = new Posts();
return $this->render('view', [
'model' => $this->findModel($id),
'ly_addPost' => $ly_addPost,
]);
}
Just Change $ly_addPost to $addpost in view file
<div class="col-md-12">
<?= $this->render ('_form', [
'addpost' => $addpost,
])
?>
...

YII2 - Column filter in index.php won't work

I've modified the index.php to show name instead the id's.
This is my orders/index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\ArrayHelper;
use frontend\models\Statuses;
$this->title = Yii::t('app', 'Ordini');
$this->params['breadcrumbs'][] = $this->title;
$user = Yii::$app->user->identity;
?>
<div class="orders-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?php
if ($user->role == 10 || $user->role > 40)
echo Html::a(Yii::t('app', 'Nuovo'), ['create'], ['class' => 'btn btn-success']);
?>
</p>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['attribute'=>'customer_id', 'value'=>'CustomersName',],
['attribute'=>'product_id', 'value'=>'ProductsName',],
'date',
[
'attribute'=>'status_id',
'value'=>'StatusesName',
'filter' => Html::activeDropDownList($searchModel, 'status_id', ArrayHelper::map(Statuses::find()->asArray()->all(), 'id', 'name'),['class'=>'form-control','prompt' => 'Select Category']),
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?></div>
Filter doesn't work. I've tryed with dropdown or only number with no success.
I don't know how to check where it fail!
In OrdersSearch? In the model or controller?
Thank you
You don't have to provide the whole code for the dropdown field. This should be enough:
'filter' => ArrayHelper::map(Statuses::find()->asArray()->all(), 'id', 'name'),

Yii2 - Grid view shows all the datas when using search

I have created a Global Search with grid view displaying, but this is the problem for the first time that the search page loads or when the search field is empty and you search, all the data in the db will be displayed.
and I have used the _search.php view inside another view.
_search view:
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'globalSearch') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
the main view:
<?php echo $this->render("../ads/_search", ['model' => $model]); ?>
<?php Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'showOnEmpty' => false,
'summary' => '',
'showFooter' => false,
'showHeader' => false,
'columns' => [
'name',
'type',
'explanation',
'address',
'province_name',
'cost',
],
]);?>
<?php Pjax::end(); ?>
Anything else is needed? Let me know.
If you want to display the grid, let the filter model return a data provider with no results when global search is empty
class FilterModel extends Model {
public $globalSearch;
::
::
public function search($params) {
$provider = new ActiveDataProvider(
$query = SomeModel::find();
);
if (!$this->globalSearch) {
$query->where('1=0'); // returns no results
return $provider;
}
// other code to return results with filter applied
::
::
return $provider;
}
}
I don't know how you applied this globalSearch filter, but this is default behavior of grid filters: when filters not defined - GridView will display matched data items (=== all items).
But if you want change this behavior you can simply not render GridView in the case of empty filter:
<?php echo $this->render("../ads/_search", ['model' => $model]); ?>
<?php
if(!empty($model->globalSearch)){
Pjax::begin();
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'showOnEmpty'=>false,
'summary'=>'',
'showFooter'=>false,
'showHeader' => false,
'columns' => [
'name',
'type',
'explanation',
'address',
'province_name',
'cost',
],
]);
Pjax::end();
}
?>

Filter copy parameters in URL

I create filter form for my data using data provider and search model and have a problem, when my filter parameters copy in url when I click submit button more than one time.
Model's ApartmentsSearch search method:
public function search($params)
{
$query = Apartments::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'rooms' => $this->rooms,
]);
return $dataProvider;
}
Controller actionIndex method:
public function actionIndex()
{
$searchModel = new ApartmentsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->get());
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
}
View with ListView widget:
<?= $this->render('_filter', ['searchModel' => $searchModel]); ?>
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_list',
'options' => [
'tag' => 'div',
'class' => 'apartments-list',
],
'layout' => '{summary}{items}{pager}',
'summary' => 'Показано квартири: <b>{begin}-{end}</b> з <b>{totalCount}</b>.',
'summaryOptions' => [
'tag' => 'div',
'class' => 'summary',
],
'itemOptions' => [
'tag' => 'div',
'class' => 'apartment-item',
],
]); ?>
And _filter.php view with form:
<?php $form = ActiveForm::begin([
'method' => 'get',
]); ?>
<?= $form->field($searchModel, 'rooms') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
So, when I input any number in field and click submit I see url like this:
http://localhost/?ApartmentsSearch[rooms]=2
When I click second time I see url with copied parameter:
http://localhost/?ApartmentsSearch[rooms]=2&ApartmentsSearch[rooms]=2
I don't want copy parameters in url, I need to change value of any parameter.
Can you help me?
Solved.
In active form I forgot add action property:
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($searchModel, 'rooms') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>

Categories