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
Related
The model is Booking.php. I need to get data from another model called ServiceCategory.php and add a filter to it in Gridview on my index.php. I created filter on view/index.php as below.
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(app\models\Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
This is my index.php
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\grid\GridView;
use app\models\Servicecategory;
/* #var $this yii\web\View */
/* #var $searchModel app\models\BookingSerach */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Bookings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="list-booking">
<h1 class=""><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p class="form-inline text-right">
<label>Client:</label>
<?= Html::dropDownList('client', null, ArrayHelper::map($clients, 'id', 'fullname'), ['prompt' => 'Please Select', 'class' => 'form-control']) ?>
<?= Html::a('+ New Booking', ['booking/create/'], ['class' => 'btn btn-primary client-create']) ?>
</p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'value' => 'user.client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
['label' => 'Service Category', 'attribute' => 'category.name', 'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
//'numberOfDays',
//'date',
//'followUpEmail:email',
// 'followUpEmailSent:ckeckbox',
//'Status',
['attribute' => 'status', 'value' => 'Status', 'filter' => array_filter(\app\models\Booking::$statuses)],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp(this, "' . $url . '")', 'checked' => false, 'id' => 'followup'];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:15%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
},
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
},
],
],
],
]);
?>
</div>
<?php
$script = <<< JS
$('.client-create').on('click', function () {
select = $(this).prev();
if(select.val()){
location.href = $(this).attr('href')+"/"+select.val();
} else {
$(this).parent().addClass('has-error');
}
return false;
});
JS;
$this->registerJs($script);
$this->registerJs("
function followUp(e, url){
$('#modal').modal('show').find('#modalContent').load(url);
}", yii\web\View::POS_END);
?>
I can get the data to the column on gridview but the filter is not working. Can anyone help me with this?
I solved it myself. For your information I post it here. I changed the attribute as the model contains and added the value as category.name
['attribute' => 'categoryID', 'value' => 'category.name','filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')],
I have the controller code:
public function actionDownload($id) {
$download = Status::findOne($id);
$path = Yii::getAlias('#webroot').'/uploads/status/'.$download->image_web_filename;
if (file_exists($path)) {
return Yii::$app->response->SendFile($path,$download->image_src_filename);
exit;
} else {
throw new NotFoundHttpException("can't find {$download->image_src_filename} file");
}
}
I have the view code in the GridView:
['attribute'=>'Download',
'format'=>'raw',
'value' => function($data)
{
return
Html::a('Download file', ['status/download','id'=>$data->id],['class' => 'btn btn-primary']);
}
],
This is what displayed on the screen.The pdf is only downloaded when the I refresh the browser but this still remains on the screen what is the problem?:
%PDF-1.4 %�쏢 5 0 obj <> stream x��]K�%ECű%P4���y��.�u�#�Q �zt��P�0��_��'��gx����/3�n���zܞ���xaAR7o�s�<�;�����܈�o��w?8��]�y�/'�O�FU��#b㍤���G����͇'r����4�+B��{3���SW����'��<�������A�ǃ*x���N27r�$���V������w�_?��k�~���+�'wFr6��f! ��ȍ7�Ӡ���UG���g;=�2�j��Ǒ �oƱQƇfh�?�WҘ�0۟��/�l�E���i(�{��* ��'�W��8��T�j 2��p������\��aܵH�$�Ci��u��$j��QZ���aIk����\o���D2Y)�/FV��nġ�a����� �_ؐ��rf�� �7�*� �IN�J{�l����Cqr�D�������[�]9���E�7�����k�j���9N�\�EC��F����&ռ-����uJV����3����L!�f��x���F�����̈́��#��U����:*g��&C�ӤD��q�17�#Jg+�J����w��ߨ?M_�a���R�ݼ��zu%��\�#�7$M&���-dO"#�]�i�89�}��<��� m��04�I�bHJ �O�M��`f�Ϯ�E�{2}`���n�����.l���+cZ?�����6C��N��XZJW�ylȒ��"�D�ͧ�8s���q��om��ݍx�6(��T�9Uɨ�g���x���\���'�Ͻ����BE��|��� p���9P]��R*����C��������jC�m���1��#K���Y���rt=�:�x����W����qr�便p4��"��B�}=�2������p��!x+�)zv���̳���\^*�R�ugȎ!J<��q�~���C��/��ˏU8�C7A0`�6x����6ۗ#�b���Ħ�(��Sk̍�"|����9�" �G�`#LD���e�B�Q���� d��[q�Z�aځ��-j�����Zk�}F4���l���y�T ��B��|���ҕ~/����a�+�7��Ai=W���1�
The problem that I had in this specific code is that I had to remove
<?php Pjax::begin(); ?> and <?php Pjax::end(); ?> and also 'pjax'=>true above and in the gridview column so that it worked I didnt alter anything in the actionDownload($id) code
Before editing(original erroneous code)
`....................................
<h3><?= Html::encode($this->title) ?></h3>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?>
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
'id',
'message',
'permissions',
'created_by',
'created_at',
// 'updated_at',
// 'image_src_filename',
//'image_web_filename',
['attribute'=>'Download',
'format'=>'raw',
'value' => function ($data) {
return
Html::a('Download file', ['status/download','id'=>$data->id], ['class' => 'btn btn-primary']);
}
],
];
?>
<?php
$export = ExportMenu::widget([
'dataProvider' => $dataProvider,
//'columns' => $gridColumns,
'fontAwesome' => true,
'exportConfig' => [
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_TEXT => false,
ExportMenu::FORMAT_CSV => false,
ExportMenu::FORMAT_EXCEL => false,
ExportMenu::FORMAT_EXCEL_X => false,
],
]);
?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
'toolbar' => [
$export
],
'pjax' => true,
'bordered' => true,
'striped' => true,
'responsive' => true,
'floatHeader' => true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => 'Forms Uploaded by Clients.',
],
]);
?>
<?php Pjax::end(); ?></div>`
After editing(original erroneous code)
`
<h3><?= Html::encode($this->title) ?></h3>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php
$gridColumns = [
['class' => 'kartik\grid\SerialColumn'],
'id',
'message',
'permissions',
'created_by',
'created_at',
// 'updated_at',
// 'image_src_filename',
//'image_web_filename',
['attribute'=>'Download',
'format'=>'raw',
'value' => function ($data) {
return
Html::a('Download file', ['status/download','id'=>$data->id], ['class' => 'btn btn-primary']);
}
],
];
?>
<?php
$export = ExportMenu::widget([
'dataProvider' => $dataProvider,
//'columns' => $gridColumns,
'fontAwesome' => true,
'exportConfig' => [
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_TEXT => false,
ExportMenu::FORMAT_CSV => false,
ExportMenu::FORMAT_EXCEL => false,
ExportMenu::FORMAT_EXCEL_X => false,
],
]);
?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'containerOptions' => ['style' => 'overflow: auto'], // only set when $responsive = false
'toolbar' => [
$export
],
'bordered' => true,
'striped' => true,
'responsive' => true,
'floatHeader' => true,
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => 'Forms Uploaded by Clients.',
],
]);
?>`
Thats all !! I found out.
Just add
ob_clean();
before
return Yii::$app->response->SendFile($path,$download->image_src_filename);
.
ob_clean() will clean your output and fix the problem .
It worked for me.
Thanks
It is look like you need header for that.
try with this code:
public function actionDownload($id) {
header("Content-type:application/pdf");
........
if is not working try to add this header too
header("Content-Disposition:attachment;filename='filename.pdf'");
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(); ?>
I am new in yii2, Right now i am creating sample crud appliacation. I used pjax for gridview, It is working fine for me, My problem is when i update my row at that time pjax also calling now i want to disable this pjax for update button. How can i resolve this issue ? Here is my code
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\PostSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Posts';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="post-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Post', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php \yii\widgets\Pjax::begin(
['id' => 'StickerList', 'timeout' => false, 'enablePushState' => false, 'clientOptions' => ['method' => 'GET']]
); ?>
<?= GridView::widget([
'dataProvider' => $model->search(),
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'PostType',
'filter'=>Html::activeDropDownList($model, 'PostType',array(""=>"All","1"=>"Status","2"=>"Images","3"=>"Video"),['class'=>'form-control','prompt' => 'Select Post Type']),
],
'PostTitle',
[
'header' => 'Artist',
'attribute' => 'ArtistName',
],
[
'header' => 'Date Posted',
'attribute' => 'DatePosted',
'filter' => false,
],
[
'header' => '# Likes',
'attribute' => 'TotalLikes',
'filter' => false,
],
[
'header' => '# Comments',
'attribute' => 'TotalComments',
'filter' => false,
],
[
'header' => 'Exclusive',
'attribute' => 'IsExclusive',
'filter'=>Html::activeDropDownList($model, 'IsExclusive',array(""=>"All","0"=>"Normal","1"=>"Exclusive"),['class'=>'form-control','prompt' => 'Select Exclusive']),
],
[
'header' => 'Status',
'attribute' => 'Status',
'filter'=>Html::activeDropDownList($model, 'Status',array(""=>"All","1"=>"Active","2"=>"Inactive"),['class'=>'form-control','prompt' => 'Select Status']),
],
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url);
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end(); ?>
</div>
You should need to add [ 'data-pjax' => false ] or [ 'data-pjax' => '0' ] in anchor tag options of update button.
For example,
[
'class' => 'yii\grid\ActionColumn',
'template'=>'{update}',
'buttons' => [
'update' => function ($url,$model) {
$url = Url::toRoute('post/update?id='.$model['PostID']);
return Html::a('<span class="glyphicon glyphicon-pencil"></span>',$url, ['data-pjax' => '0']);
},
],
]
Recently I installed the multiSelect check box extension.
my _form.php looks like this:
<? = $ Form-> field ($ model_detail, 'product_id') ->
widget (MultiSelect :: className (),
['id' => "multiXX",
"options" => ['multiple' => "multiple"],
'data' => $ rows,
'attribute' => 'product_id',
'model' => $ models ,
"clientOptions" =>
[
"includeSelectAllOption" => true, 'numberDisplayed' => 2,
],
]);
How can I extract the data chosen by the user in actionCreate of anther model?
how can I get the options that the user selected?
(I tried the $_post[] and it didn't worked.)
this is the whole form:
div class="customer-order2-form">
<?php $form = ActiveForm::begin(['action' => ['create']]); ?>
<?= $form->field($model, 'customer_name')->textInput(['maxlength' => 255]) ?>
<?= $form->field($model, 'customer_phone')->widget(\yii\widgets\MaskedInput::className(),
[
'mask' => '999-9999999',
'clientOptions' => ['alias' => '972']
]) ?>
<?php /* $form->field($model, 'customer_phone')->textInput(['maxlength' => 255]) **/?>
<?= $form->field($model, 'order_date')->widget(
DatePicker::className(), [
'inline' => false,
// 'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-m-d'
]
]);?>
<?php $model_detail = new OrderDetails2(); /* -------- כאן הוספתי נתונים ממודל
$rows=ArrayHelper::map(ProductFamily::find()->all(), 'id', 'name'); //--- אין צורך בשאילתא, עכשיו גם מציג את מה שנבחר למעלה
?>
<?= $form->field($model_detail, 'product_id')->widget(
MultiSelect::className(), [
'id'=>"multiXX",
"options" => ['multiple'=>"multiple"], // for the actual multiselect
'name' =>'multicheck',
'data' =>$rows,
'attribute' => 'product_id', // if preselected
'model' => $models,
"clientOptions" =>
[
"includeSelectAllOption" => true,
'numberDisplayed' => 2,
],
]);
?>
<?php
echo $form->field($model, 'description')->textarea(['rows' => 6]);
echo /*$form->field($model, 'totalprice')->textInput();*/
$form->field($model, 'totalprice')->widget(MaskMoney::classname(), [
'pluginOptions' => [
'prefix' => '₪ ',
'allowNegative' => false
]
]);
echo $form->field($model, 'status_id')->dropDownList(ArrayHelper::map(Status::find()->select('*')->all(), 'id', 'name'));
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'יצירה' : 'עדכון', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
what i tried is saving to different table in DB with a default Array,
and it worked.
it looks like this:
public function actionCreate()
{
$model = new CustomerOrder2();
$model_details= new OrderDetails2();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
if (isset($_POST['product_id'])){
$model_details->attributes = $_POST['product_id'];
$model_details->attributes=array();
echo
$model_details->attributes;
}
echo $_POST['description'];
$values = Array('1'=>'1','2'=>'2');
$model_details->attributes = $_POST['product_id'];
$array=$model_details->attributes;
//$data=OrderDetails2::->request->post();
//$values= Array(Yii::$app->request->post()['multiXX']);
//$values=Array($model_details->attributes);
foreach($values as $value)
{
$command = Yii::$app->db->createCommand();
$command->insert('order_details',array('Order_id'=>$model->id,
'product_id'=> $value,
'quantityOrdered'=> '1',
));
$command->execute();
}
return $this->redirect(['view', 'id' => $model->id]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}