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

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.

Related

Yii2 Pjax Gridview in Modal will reload page instead of updating

I had a problem with Pjax, actually on somepage I load a view in Modal, and in this modal I use GridView with filter option with selectbox. When user changes the filter, the content will not be updated, but the page will be redirected to the filtered URL (Gridview with data updated).
When the view is working outside the modal it works fine, and update its contents!
Here is my code:
index.php, here I load my modal:
<div>
<?php
Modal::begin([
'header' => '',
'id' => 'modal-window',
'class' => 'modal',
'footer' => 'Close',
'clientOptions' => ['backdrop' => false]
]);
Modal::end();
?>
And in view:
<?php Pjax::begin(['id' => 'pjax_translation','enablePushState' => false, 'timeout' => false,]); ?>
<div class="row">
<h1><?= Html::encode($this->title) ?></h1>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterUrl' => Url::to(["translate/view" , "id" => $id ]),
'tableOptions' => ['class' => 'table table-striped table-bordered translate-list',"style"=> ""],
'options' => ['data-pjax' => true ],
'columns' => [
[
'attribute' => 'language',
'filter' => $arrLanguage,
'content'=> function($model) use ($arrLanguage){
return isset($arrLanguage[$model->language])? $arrLanguage[$model->language] : "" ;
},
'headerOptions' => ['width' => '150'],
],
[
'attribute' => 'translation',
],
],
]); ?>
</div>
<?php Pjax::end(); ?>
And in my controller the code is:
public function actionView($id)
{
$view = "view";
$searchModel = new TranslateMessageSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andFilterWhere([
'id' => $id,
]);
if (Yii::$app->request->isAjax) {
\Yii::$app->response->format = 'json';
$html = $this->renderAjax($view, [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'id'=>$id,
]);
return ['success' => true, 'html' => $html] ;
} else {
return $this->render($view, [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'id'=>$id,
]);
}
}
i found finally a solution after three days testing everything. I will post it here, maybe it could be usefull for someone who has the same problem.
I just put in my view.php the following js at the top:
$js = "$(document).on('submit', 'form[data-pjax]', function(event) {
$.pjax.submit(event, '#pjax_translation', {
'push': false,
'replace': false,
'timeout': 5000,
'scrollTo': false,
'maxCacheLength': 0
});
});";
$this->registerJs($js);
and everything is work fine now :)
this is working for me:
<?php Modal::begin([
'header' => '',
'id' => 'modal-window',
'class' => 'modal',
'toggleButton' => ['label' => 'click me'],
'footer' => 'Close',
'clientOptions' => ['backdrop' => false]
]); ?>
<?php Pjax::begin() ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => 1]]) ?>
<?= date('Y-m-d H:i:s', time()) ?> <button type="submit">click this</button>
<?php ActiveForm::end() ?>
<?php Pjax::end() ?>
<?php Modal::end(); ?>
PS: Maybe your page gets reloaded because you hit Pjax timeout

How to Add Filter Search Like Grid View In List View Yii2

I Want to Add Filter With List View (Some Thing Like What Is In Grid View) but I Don Not Know How Do That
Filters I Want Are CheckBox And DropDown Options.
Here Is My Action Code In SiteController
<?php
public function actionMobiles(){
$searchModel = new MobileSearch();
//$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider = new ActiveDataProvider([
'query' => Mobile::find(),
'pagination' => [
'pageSize' => 1,
],
]);
// get the posts in the current page
//$posts = $dataProvider->getModels();
return $this->render('mobiles', ['dataProvider' => $dataProvider,'searchModel' => $searchModel]);
}
?>
In View File I Have 2 Files :
Here Is mobiles View :
<?php
use yii\widgets\ListView;
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\ArrayHelper ;
use app\models\Mobile;
?>
<?= ListView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'itemView' => '_mobiles',
]); ?>
And In _mobiles I Have :
<?php
use yii\widgets\DetailView;
?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
//'id',
'id',
'title',
//'ativo',
],
]) ?>
It Shows Data From DataBase Correctly With It Pagination.
But How To Add Filter To Update List(CheckBox And DropDown List Are Use to Update)??
here is the code for you, you should replace attribute and model name according to yours.
[
'attribute' => 'attribute_name',
'label' => 'Email',
'value' => function($model){
return $model->attribute_name;
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => \yii\helpers\ArrayHelper::map([Your Model]::find()->asArray()->all(), 'id', 'email'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Email', 'id' => 'grid--search-email']
],
Add this line in your view file,
Just above listview widget
echo $this->render('_search', ['model' => $searchModel]);

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

Yii2 Pjax reloads entire page on second form submit

I cannot seem to figure out why pjax reloads the page on the second form submission. It works exactly as intended on the first form submission pulling from this url /site/profile?UserSearch%5Bsearchstring%5D=mi&_pjax=%23form-pjax, however, after that first one it loses the ending of the url /site/profile?UserSearch%5Bsearchstring%5D=m. I checked the actual html code and the form is retaining the data-ajax attribute. I tried increasing the timeout as had been suggested when pjax is reloading the entire page, but that did not change anything.
Below is the code from my view
<?php Pjax::begin(['timeout' => 5000, 'id' => 'form-pjax']); ?>
<?php $form = ActiveForm::begin([
'method' => 'get',
'action' => Url::to(['site/profile']),
'options' => ['data-pjax' => true ],
]); ?>
<?= $form->field($searchModel, 'searchstring', [
'template' => '<div class="input-group">{input}<span class="input-group-btn">' .
Html::submitButton('Search', ['class' => 'btn btn-default']) .
'</span></div>',
])->textInput(['placeholder' => 'Find friends by username or email']);
?>
<?php ActiveForm::end(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'username',
[
'label' => 'View Profile',
'format' => 'raw',
'value'=>function ($data) {
return Html::a(Html::encode("View Profile"),'/site/redirectprofile/'.$data->id);
},
],
[
'label' => 'Follow',
'format' => 'raw',
'value'=>function ($data) {
return Html::a(Html::encode(Follow::find()->where(['user_id' => $data->id, 'follower_id' => Yii::$app->user->Id])->exists() ? 'Unfollow' : 'Follow'),'/site/follow/'.$data->id.'/'.$data->username);
},
],
],
'summary'=>'',
]); ?>
<?php Pjax::end(); ?>
You must call needed javascript triggers/functions after every pjax reload like:
$('#form-pjax').on('pjax:success', function() {
/*call Your functions here, or copy from your generated page js code,
that bind event to pjax form,
at end of generated html You should have something like: */
jQuery(document).on('submit', "#form-pjax form[data-pjax]", function (event) {
jQuery.pjax.submit(event, '#form-pjax', {"push":true,"replace":false,"timeout":000,"scrollTo":false});
});
});
This is not yii2 issue, it's how javascript works, when You add dynamically content it's needed to bind triggers/events for every added element.

Outputting data from table after saving with ckeditor

Am saving data using the ckeditor in yii2 in my form model but when doing the view action it displays the html tags
CKEDITOR CODE:
<?= $form->field($model, 'case_description')->widget(CKEditor::className(),[
'editorOptions' => [
'preset' => 'full',
'inline' => false,
],
]);
?>
So after I save the data in the table its saved having the html codes
example of saved data:
<b>My new project being grilled</b>
So when viewing the data using yii2 detail and gridview it always shows the <b> instead of being bold.
How can I solve the problem
EXAMPLE: of grid view outputting it in the case_description column
<?= GridView::widget([
'summary'=>"",
'showOnEmpty'=>false,
'dataProvider' => $dataProviderb,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'case_description',
],
]) ?>
You just use the 'format' => 'row' in your GridView like:
<?= GridView::widget([
'summary'=>"",
'showOnEmpty'=>false,
'dataProvider' => $dataProviderb,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'case_description',
'format' => 'raw',
],
],
]) ?>

Categories