Set enablePushState = false on specific urls inside Pjax container (Yii2) - yii2

I need pjax to work on change status click and it's working fine but don't want it to change the URL as well. Below is the code:
<?php Pjax::begin(['id'=>'pjax-container-agency-index', 'timeout' => 10000, 'enablePushState' => true]); ?>
<?= GridView::widget([...,
[
'label' => 'Status',
'format' => 'raw',
'value' => function ($data) {
if ($data->deactive == 0) {
return Html::a(FA::i('circle'), ['agency/change-status', 'id' => $data->member_id, 'set' => 1], ['onclick' => "return confirm('Deactive this state/site?');", 'class' => 'status-inactive']);
} else {
return Html::a(FA::i('circle'), ['agency/change-status', 'id' => $data->member_id, 'set' => 0], ['onclick' => "return confirm('Active this state/site?');", 'class' => 'status-active']);
}
},
],
]);
<?php Pjax::end(); ?>
actionChangeStatus() is as below:
public function actionChangeStatus($id, $set) {
if (!empty($id) && isset($set)) {
$localGovt = $this->findModel($id);
$localGovt->deactive = $set;
if ($localGovt->save()) {
Yii::$app->getSession()->setFlash('success-status', 'State Status Changed');
} else {
Yii::$app->getSession()->setFlash('error-status', 'There is some error. Please consult with Admin.');
}
$searchModel = new AgencySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider
]);
}
}
Note: I need 'enablePushState' => true for other events, so I can't change it to false inside Pjax::begin

I believe it's
'enableReplaceState' => true

Pass this attribute to Pjax:
Pjax::begin(['enablePushState' => false]);
This worked for me.

Related

how insert Initial value in yii2 ckeditor

<?=
$form->field($model, 'template')->widget(CKEditor::className(), [
'options' => ['rows' => 100],
'preset' => 'full',
'value'=>'<p>Incercam sa editam</p>',
])->label(true)
?>
This is my code
I need to set initial value in editor
You should assign a value in your field template eg in you controller/create
public function actionCreate()
{
$model = new YourModel();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->template ="your initila value ....... text "
return $this->render('#common/views/antigone-contribuente/create', [
'model' => $model,
]);
}
}
once you have assigne to youe $model->template the value you need yuo should see this in your editor in view

Searching records for date fails

Following code should search records for date. But whatever I click,main branch in condition will be executed,so I will get outprinting:
choice_date is false
It will be searched for records which are <=department_created_date,but never for records >=department_created_date
Any ideas,how to fix this?
Here is my RadioList
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\ActiveForm;
$this->title = Yii::t('app', 'Departments');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="departments-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php
$form = ActiveForm::begin();
$model = new backend\models\DepartmentsSearch();
?><?= $form->field($model, 'choice_date')->radioList(array(0 => 'Before', 1 => 'After'))->label('Please, choose Datesearching!'); ?>
<p><?= Html::a(Yii::t('app', 'Create Departments'), ['create'], ['class' => 'btn btn-success']) ?></p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'branches_branch_id',
'label' => Yii::t('app', 'Branch'),
'value' => function($model) {
if ($model->branches_branch_id) {
return $model->branchesBranch->branch_name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => backend\models\Branches::getBranchList(),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Branch', 'id' => 'grid-Branch-search-rechtsart']
],
'branchesBranch.branch_name',
'department_name',
[
'attribute' => 'companies_company_id',
'label' => Yii::t('app', 'Company'),
'value' => function($model) {
if ($model->companies_company_id) {
return $model->companiesCompany->company_name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => backend\models\Companies::getCompanyList(),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Company', 'id' => 'grid-Company-search-rechtsart']
],
'department_created_date',
['class' => 'yii\grid\ActionColumn'],
],
]);
?>
</div>
and here is my searching class:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Departments;
class DepartmentsSearch extends Departments {
public $choice_date;
public function rules() {
return [
[['department_id'], 'integer'],
[['choice_date'], 'boolean'],
[['department_name', 'department_created_date', 'department_status', 'companies_company_id', 'branches_branch_id'], 'safe'],
];
}
public function scenarios() {
return Model::scenarios();
}
public function search($params) {
$query = Departments::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate())
return $dataProvider;
/*
Whatever I click in RadioList,property will be 0,so I'll get setFlash->'choice_date is false'
*/
if ($this->choice_date == 0) {
Yii::$app->session->setFlash('If-branch is false', 'choce_date is false');
$query->andFilterWhere(['<=', 'department_created_date', $this->department_created_date]);
} else {
Yii::$app->session->setFlash('if-branch is true', 'choice_date is true');
$query->andFilterWhere(['>=', 'department_created_date', $this->department_created_date]);
}
$query->joinWith('companiesCompany');
$query->joinWith('branchesBranch');
$query->andFilterWhere(['like', 'department_name', $this->department_name])
->andFilterWhere(['like', 'companies.company_name', $this->companies_company_id])
->andFilterWhere(['like', 'branches.branch_name', $this->branches_branch_id])
->andFilterWhere(['like', 'department_status', $this->department_status]);
return $dataProvider;
}
}
Further ideas,how to fix this misery?
P.S.: For Bizley's help, here is an extraction of my controller:
class DepartmentsController extends Controller{
public function actionIndex(){
$searchModel = new DepartmentsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
further methods are irrelevant,here. Why will property of date-record not be rendered in view?
}
Your $model in the view is RadioForm so the form sends this field as RadioForm[choice_date].
But you are expecting choice_date from DepartmentsSearch model and this field is left empty.
Remove the RadioForm model, it's totally unneeded. Use DepartmentsSearch model in the form view.
Update:
Since OP finally told that this is a GridView I can update my answer to suit him.
There is filterSelector property in GridView you can use - you can set there additional jQuery selectors that will be used for filtering.
Here is updated code with comments below:
<?php $form = ActiveForm::begin();
echo $form->field($searchModel /* 1 */, 'choice_date')->radioList([
0 => 'Before', 1 => 'After'
], ['itemOptions' => ['class' => 'choiceRadio' /* 2 */]])->label('Please, choose Datesearching!');
ActiveForm::end(); /* 3 */ ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterSelector' => '.choiceRadio', /* 4 */
// ...
This is the $searchModel I was talking about. You don't need any other model here.
You can set here any CSS class you want, it's for filterSelector.
Don't forget to close form like you did in your original code.
This is the selector for the radio input. Mind the notation - . for CSS class, # for CSS id.

Yii2 Dynamic form update fail on kartik-Select2

I am using wbraganca dynamic form widget. It works fine for the Create action.
Let me thanks for those guys making great tutorial video on youtube!!!
I am working on the Update action now. I work it on a purchase order function.
the controller of update action :
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsItem = $model->purchaseitems;
if ($model->load(Yii::$app->request->post()) ) {
$oldIDs = ArrayHelper::map($modelsItem, 'purchaseitem_id', 'purchaseitem_id');
$modelsItem = Model::createMultiple(Purchaseitem::classname(), $modelsItem);
Model::loadMultiple($modelsItem, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsItem, 'purchaseitem_id', 'purchaseitem_id')));
$valid = $model->validate();
$valid = Model::validateMultiple($modelsItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Purchaseitem::deleteAll(['purchaseitem_id' => $deletedIDs]);
}
foreach ($modelsItem as $modelItem) {
$modelItem->purchaseitem_purchaseorder_id = $model->purchaseorder_id;
$modelItem->purchaseitem_description = Inventory::findOne($modelItem->purchaseitem_inventory_id)->inventory_partno;
if (! ($flag = $modelItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->purchaseorder_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
//return $this->redirect(['view', 'id' => $model->purchaseorder_id]);
} else {
return $this->render('update', [
'model' => $model,
'modelsItem' => (empty($modelsItem)) ? [new Purchaseitem] : $modelsItem
]);
}
}
But I think the problem may happen on the view file, as the Select2 field can show the value, which is the 'id' of the product rather than the product code.
view:
<div class="panel panel-default">
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.container-items',
'widgetItem' => '.item',
'limit' => 50,
'min' => 1,
'insertButton' => '.add-item',
'deleteButton' => '.remove-item',
'model' => $modelsItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'purchaseitem_inventory_id',
'purchaseitem_qty',
'purchaseitem_cost_usd',
'purchaseitem_deliverydate',
],
]); ?>
<?php foreach ($modelsItem as $i => $modelItem): ?>
<div class="item">
<?php
// necessary for update action.
if (! $modelItem->isNewRecord) {
echo Html::activeHiddenInput($modelItem, "[{$i}]purchaseitem_id");
}
?>
<div class="row">
<?= $form->field($modelItem, "[{$i}]purchaseitem_inventory_id")->widget(
Select2::classname(), [
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 2,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Error on finding results...'; }"),
],
'ajax' => [
'url' => Url::toRoute('inventory/inventorylist'),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
'templateSelection' => new JsExpression('function (purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
],
])->label(false) ?>
<?= $form->field($modelItem, "[{$i}]purchaseitem_qty")->textInput(['maxlength' => true])->label(false) ?>
<?= $form->field($modelItem, "[{$i}]purchaseitem_cost_usd")->textInput(['maxlength' => true])->label(false) ?>
<?= $form->field($modelItem, "[{$i}]purchaseitem_deliverydate")->widget(
DatePicker::className(), [
'options' => [
['placeholder' => 'Please enter delivery date'],
],
'removeButton' => false,
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd',
'todayHighlight' => true,
]
]
)->label(false) ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
I have a thought that the problem maybe related to that few lines of JsExpression function.
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
'templateSelection' => new JsExpression('function (purchaseitem_inventory_id) { return purchaseitem_inventory_id.text; }'),
For the Select2 query URL method is here:
public function actionInventorylist($q = null, $id = null) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if (!is_null($q)) {
$query = new Query;
$query->select('inventory_id AS id, inventory_partno AS text')
->from('inventory')
->where(['like', 'inventory_partno', $q])
->limit(10);
$command = $query->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > 0) {
$out['results'] = ['id' => $id, 'text' => Inventory::find($id)->inventory_partno];
}
return $out;
}
I can load the record, when I click in the update view. Most of the data are feed in right place of the form, except the 'partno' field. I use Select2 to let user select partno by text and store the 'id' in table. It works on the Create view.
but in the update view, it only show the 'id' instead of the 'partno'.
if I make input to the field, I can select 'other' partno only, let me explain here:
if there are 2 code, "ABC" with 'id' is 1, "XYZ" with 'id' 2.
the record original is "ABC", the field show "1".
If I input "XYZ", it will show "XYZ" as normal effect of widget. But, if I change back to "ABC", it will show "1" instead of "ABC".
And the form also cannot submit for update. the button click with no effect.
I am new to Yii2 framework, and quite stuck on this issue, does anyone knows how can I solve this?
THANKS!!!!
I just solve the problem, a few issue happened actually.
To solve the Select2 widget cannot display the partno instead of the ID, I find the partno by the ID and feed it with initValueText in Select2. For my case:
$partno = empty($modelItem->purchaseitem_inventory_id) ? '':Inventory::findOne($modelItem->purchaseitem_inventory_id)->inventory_partno;
$form->field($modelItem, "[{$i}]purchaseitem_inventory_id")->widget(Select2::classname(), ['initValueText' => $partno, ...
About the update POST fail issue, I got error of Getting unknown property: backend\models\Purchaseitem::id, and I found it happened on the Dynamic-form widgets Model.php line 25. That lines is $keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
If I change the 'id' to my ID field name, i.e 'purchaseitem_id', it will work, but this model will only work for this Id field name afterward. So I get the model's primaryKey and make it work for my other model.
add this line $primaryKey = $model->tableSchema->primaryKey; and modify above line $keys = array_keys(ArrayHelper::map($multipleModels, $primaryKey, $primaryKey));

How to use Pjax with a Custom Button in Gridview

This is my gridview
<?php Pjax::begin(['id' => 'vouchers']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['header'=>'Cancel Voucher',
'value'=> function($data)
{
return Html::a(Yii::t('app', ' {modelClass}', [
'modelClass' =>"Cancel",
]), ['generalentries/cancel_voucher','voucher_no'=>$data->voucher_no],
['class' => 'btn btn-xs btn-danger',
'onclick'=>"return confirm('Are you Sure you want to CANCEL this Voucher?');"]
);
},
'format' => 'raw'
],
],
]); ?><?php Pjax::end() ?>
and this is my cancel_voucher action
public function actionCancel_voucher( $voucher_no )
{
$entries = TabGLEntry::find()->where(['voucher_no' => $voucher_no])->all();
foreach($entries as $entry)
{
$entry->update_note = FALSE;
$entry->is_deleted = 1;
$entry->save();
}
$this->redirect( Yii::$app->request->referrer );
}
How can i update the grid view using pjax when i click on the Cancel Button?
I tried giving button an id and then on the onClick event of the button i tried to update the gridview using $.pjax.reload({container:"#vouchers"}); But it didn't work
EDIT
This is how i tried
<?php
\yii\widgets\Pjax::begin([
'id' => 'countries',
'timeout' => false,
// 'enablePushState' => false,
'clientOptions' => ['method' => 'POST']])
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['header'=>'Cancel Voucher',
'value'=> function($data)
{
return Html::a(Yii::t('app', ' {modelClass}', [
'modelClass' =>"Cancel",
]), ['generalentries/cancel_voucher','voucher_no'=>$data->voucher_no],
['class' => 'btn btn-xs btn-danger','id' =>'cancel_voucher',
'onclick'=>"return confirm('Are you Sure you want to CANCEL this Voucher?');"]
);
},
'format' => 'raw'
],
<?php
$this->registerJs(
'jQuery(document).ready(function($){
$(document).ready(function () {
$("#cancel_voucher").on("click", function(){
alert("hai");
$.pjax.reload({container:"#countries"});
});
});
});'
);
?>
Issue
You have to return content, which will be showing in Pajax block instead of $this->redirect( Yii::$app->request->referrer );
public function actionCancel_voucher( $voucher_no )
{
$entries = TabGLEntry::find()->where(['voucher_no' => $voucher_no])->all();
foreach($entries as $entry)
{
$entry->update_note = FALSE;
$entry->is_deleted = 1;
$entry->save();
}
if (Yii::$app->getRequest()->getIsPjax()) {
//render part of view with grid
return $this->renderAjax($url, $params);
}
else { $this->redirect( Yii::$app->request->referrer ); }
}
For correct pajax redirect you have to setup X-Pjax-Url header.
if (Yii::$app->getRequest()->getIsPjax()) {
$response = Yii::$app->getResponse();
$destination = Url::to($url);
$response->getHeaders()->set('X-Pjax-Url', $destination);
$response->getHeaders()->set('Location', $destination);
return null;
}

yii2 Pjax + java script prompt

It there any way to make 'data-confirm' => Please enter the number' not just confirm but some like JS prompt and get imputed values to sent it to controller?
<?php \yii\widgets\Pjax::begin(['id' => 'pjax-orders_table','clientOptions' => ['method' => 'POST'], 'enablePushState'=>false]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'id'=>'orders_table',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
///some columns
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}{some}',
'buttons' => [
'some' => function ($url,$model,$key) {
if($model->status=='not confirm')
{
return Html::a('<span class="glyphicon glyphicon-trash"</span>',['my/some', 'id' => $model->id],[
'title' => Yii::t('yii', 'Delete'),
'data-confirm' => Please enter the number',
'data-method' => 'post',
]);
}
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end() ?>
In controller
public actionSome()
{ $dataProvider = new ActiveDataProvider();
$dataProvider->query = Orders::find()->all();
return $this->render('some',['dataProvider'=>$dataProvider]);
}
instead of Html::a() use Html::button()where button id = some_item_id and then write this JS code
$('.buttons_class').click(function(){
var selection;
do{
selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10);
}
while(isNaN(selection));
if(!isNaN(selection))
{
$.post("some",{id:45,prompt_value:selection}, function(response)
{
console.log(response);
$.pjax.reload({container:'#pjax-orders_table'});
});
}
})