Yii2 - Grid view shows all the datas when using search - php

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();
}
?>

Related

Yii2: Search form not working with Gridview in Pjax

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);

how to add relational attributes to gridview yii2?

i have a new question yii2.
how to show relational values from other tables in gridview in views/viewname/index and also add a button to that for confirm?
thank you
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\LaptopSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Laptops';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="laptop-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Laptop', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'network',
'technology',
'sup_id',
'speaker',
// 'optical_drive',
// 'webcam',
// 'touchpad',
// 'card_reader',
// 'ethernet',
// 'vga',
// 'hdmi',
// 'usb3_ports',
// 'usb2_ports',
// 'usb_type_c',
// 'thunderbolt_ports',
// 'serial_ports',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
how to add here new attributes and also add a button?
for get the related values you can add to your model
a function for the relation
public function getYourRelatedModel()
{
return $this->hasOne(YourRelatedModel::className(), ['id' => 'your_id_fk']);
}
and the add a getter for the field you need
public function getYour_field() {
return $this->yourRelatedModel->your_field;
}
and last add to your gridview the column
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'network',
'technology',
'sup_id',
'speaker',
'your_field',
how to show relational values from other tables in gridview
Consider order and customer model
In order, model establishes the customer relationship.
public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}
Show customer name in order listing page
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Customer',
'attribute' => 'customer_id',
'value' => function($data) {
return $data->customer->name;
},
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
is there any way to make sortby link for that?
Add "attribute" to grid column it resolves the sortable problem
[
'value'=> 'customer.name',
'label' => 'Customer Name',
],
try this for showing name of customer!
if you want to sort this you need to create in searchModel a customerName fake attribute and work with it.

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'),

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(); ?>

Yii2 - Render _search.php file inside index.php of a view

i have a view folder called eventos in Yii2. This view is an image gallery.
The _view2.php is for display of the images to general public. It works quite well.
But now i want to create a globalsearch input text inside _view2.php.
There i have already a GridView widget for display the images, but i don't want to use the $searchmodel boxes so i disable them.
What i want is to render the _search.php file with just one input field, inside the _view2.php file
My problem is in rendering the _search.php inside the _view2.php file.
Here is the code for _view2.php:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showOnEmpty'=>false,
'summary'=>'',
'showFooter'=>false,
'showHeader' => false,
'bordered' => false,
'striped' => false,
'hover' => true,
//'options' => ['class' => 'grid-view'],
//'layout' => "{summary}\n{items}\n{pager}",
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
//'nome',
'descricao',
'data',
// No model -> getImageurl()
[
'label' => '',
'format' => 'raw',
'value'=> function($data) { return Html::a(Html::img($data->imageurl, ['width'=>'300', 'height' => "170"]), $data->foto); },
],
[
'label' => '',
'format' => 'raw',
'value'=> function($data) { return Html::a(Html::img($data->imageurl2, ['width'=>'300', 'height' => "170"]), $data->foto2); },
],
['class' => 'yii\grid\ActionColumn', 'template' => ''],
],
]); ?>
And i need to render the _search.php inside the _view2.php.
Code for _search.php:
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'globalsearch') ?>
Any ideas?
SOLVED.
_view2.php code:
use yii\base\view;
echo $this->render('_search', array('model'=>$searchModel));
You can use renderPartial to display a partil view inside another
For example adding this:
<?php echo $this->renderPartial('_search', array('model'=>$model)); ?>
This is an example that is generated with gii by the way
Here is the code of a file view/create.php:
<?php
/* #var $this EventsController */
/* #var $model Events */
$this->breadcrumbs=array(
'Events'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List Events', 'url'=>array('index')),
array('label'=>'Admin Events', 'url'=>array('admin')),
);
?>
<h1>Create Event</h1>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?>
As you can see the view 'create' loads the partial view '_form' that is the way you acomplish this. So you can reuse the _form view in another views like in the update view for example.

Categories