Yii2 ajax update row status and hide row after status change - ajax

I am using Yii2 gridview with custom action button. On click custom button i want to update status of that record and hide that row from gridview.
Also want to show success message.
[
'class' => 'yii\grid\ActionColumn',
'header'=>'Actions',
'template' => '{confirm}',
'buttons' => [
//view button
'confirm' => function ($url, $model) {
return Html::a('Confirm', $url, [
'title' => Yii::t('app', 'Confirm Address'),
'class'=>'btn btn-success',
]);
},
],
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'confirm') {
return Url::to(['customers/confirmaddress','id'=>$model->id]);
}
}
]

You can Pjax at beginning of GridView and configure dateProvider to show those value having status other than update Status value on confirm prompt an alert box and make your confirm button to data-pjax => true so handle pjax request and update your Pjax -container after ajax request is successfull .. provide some more extra controller code

Related

Yii2 Kartik editable input value will only change after refresh

I use Kartik Editable input widget. I have a home model and tema model attribute here. Whenever I input and submit value in the field, the value won't change on-the spot but will only change after I refresh the page instead. What should I do? Thanks!
My controller :
public function actionIndex()
{
$searchModel = new HomeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// table only has one row
$model= Home::find()->one();
// Check if there is an Editable ajax request
if (isset($_POST['hasEditable'])) {
// use Yii's response format to encode output as JSON
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
// read your posted model attributes
if ($model->load($_POST)) {
// read or convert your posted information. Based on the 'name' property set in the view. So this 'tema' of $model-> tema comes from 'name' property set in the view.
$value = $model->tema;
$model->save();
// return JSON encoded output in the below format
return ['output'=>$value, 'message'=>'output berhasil'];
// alternatively you can return a validation error
// return ['output'=>'', 'message'=>'Validation error'];
}
// else if nothing to do always return an empty JSON encoded output
else {
return ['output'=>'', 'message'=>'output gagal'];
}
};
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=>$model,
]);
}
The view
<?php
echo Editable::widget([
'model' => $model,
'attribute' => 'tema',
'value'=>$model->tema,
/*'asPopover'=>'false',*/
'type' => 'post',
'header'=>'tema',
'valueIfNull'=>'value-nya NULL',
'format'=>'link',
'size'=> 'lg',
'inputType' => Editable::INPUT_TEXT,
'editableValueOptions' => ['class' => 'text-success h3']
]); ?>
Another issue, whenever I used 'asPopover'=>'false', it shows no error but nothing happen when I click the supposedly editable-input field. The editable-inline field just won't show up. When I use the popOver option,the pop-up just automatically triggered without clicking and also it pop-up on the top left corner of the page. Only after I clicked on the editable widget that triggered the pop-up will it recorrect itself to the proper position. Is it a bug? I used the latest Yii2 with bootstrap 4, and I had set the global parameter in params.php config with 'bsVersion' => '4.x', as in the documentation
In the Controller, try this:
public function actionIndex()
{
$searchModel = new HomeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if (isset($_POST['hasEditable']))
{
$tema = Yii::$app->request->post('editableKey');
$modelHome = Home::findOne($tema);
$posted = current($_POST['Home']);
$post = ['Home' => $posted];
if ($modelHome->load($post)) {
$modelHome->save();
$out = Json::encode(['output'=>$modelHome->tema, 'message'=>'']);
return $out;
}
return;
};
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=>$model,
]);
}

Validate Select2 in Yii2 via AJAX

I have Yii2 application which uses the Kartik plugin to initialize Select2 dropdowns in forms.
I have one particular Select2 which uses AJAX call to get the data for the drop down options.
<?=
$form->field($model, 'court_house_id', ['enableAjaxValidation' => true, 'selectors' => ['input' => '#' . $id . "-court-house"],'template' => FormHelper::GenerateFieldTemplate([6])])
->widget(Select2::classname(), [
'options' => ['id' => $id . "-court-house", 'placeholder' => Yii::t('app', 'Search court house...')],
'hashVarLoadPosition' => \yii\web\View::POS_READY,
'pluginOptions' => [
'dropdownParent' => new JsExpression("$('#$modalWindowId')"),
'allowClear' => true,
'minimumInputLength' => 2,
'language' => [
'errorLoading' => new JsExpression("function () { return '" . Yii::t('app', 'Search...') . "'; }"),
],
'ajax' => [
'url' => app\components\UrlMaker::link('data/court-house-list'),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(courthouse) { return courthouse.text; }'),
'templateSelection' => new JsExpression('function (courthouse) { return courthouse.text;}'),
]])
->label(Yii::t('app', 'Court House'), ['class' => FormHelper::GenerateLabelClassTemplate([3])]);
?>
Intentionally pasting all of the code, although most of it is irrelevant I would assume.
I have this loaded in multiple dynamically created forms thus all the strange ids and selectors. However, the form has different dropdown which controls whether some of the fields are shown (and required) or not. This particular field above is only shown in one of the scenarios which all the other variations of the form do not have it. So the model has the following validation:
[['court_house_id', 'staff'], 'required', 'on' => self::SCENARIO_ONE],
By the way staff is just a regular text field and everything works for it.
In order to change the scenario, I have the following line in the view with the form:
<?php $model->scenario = \app\models\MyModel::SCENARIO_ONE; ?>
The problem is that when I submit the form empty, the staff field gets marked in red as invalid but the court house is marked in green as valid although it is empty.
If I go into the model and remove the 'on' => self::SCENARIO_ONE part then everything works as expected - on empty submit the court house field also lights up in red but that would be a problem for the rest of my scenarios where this field is not needed.
Any ideas what might be causing the problem and how to resolve it?
Try to set the scenario in controller before calling save() method, for example
$model = new MyModel(['scenario' => MyModel::SCENARIO_ONE])

Yii2 ActiveForm Ajax Validation and submit

I have made an Active form with validation and ajax submit.
The form is created in view:
<?php $form = ActiveForm::begin([
'id' => 'login-form',
'layout' => 'horizontal',
'method' => 'post',
'enableClientValidation' => false,
'enableAjaxValidation' => true,
'validationUrl' => 'panel/validate',
'fieldConfig' => [
'options' => [
'tag' => false,
],
'template' =>'{input}<p class="help-block help-block-error ">{error}</p>'
],
]); ?>
The validation action:
public function actionValidate()
{
$model = new LoginForm();
$request = \Yii::$app->getRequest();
if ($request->isAjax && $request->isPost && $model->load(Yii::$app->request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
return $this->renderAjax('login', [
'model' => $model,
]);
}
When i leave the fields blank for example, or do not specify the captcha i can see the ajax response:
{"loginform-username":["Username cannot be blank."],"loginform-password":["Password cannot be blank."],"loginform-captcha":["Captcha cannot be blank."]}
However, those errors not getting shown under my form fields. The form fields are created like this:
<?= $form->field($model, 'username')->textInput()
If i turn off ajax validation, the erros are displayed. What can be wrong here?
I'm afraid there is no possible way to display error while turning off 'tag' = false in fieldConfig.
Even though it works for server-side validation, the main problem is how yii.activeForm.js updateInput() function for fields works. When ajax request is completed, the .js tries to find an outer tag (of field) with .field-<model>-<attribute> class selector and fetch error-div children. As long as there is no outer .field tag, no error message is append to form.
I'm not 100% sure about it, but this is my understanding from debugging yii.activeForm.js functionality.
Actually, here is the similar question in yii2/issues, where SilverFire explains that there is no way to achieve this.
ActiveForm fieldConfig options tag=>false will render class attribute without any tag

Disable row clicking action helperList Prestashop

I have created a helperList and defined the rowActions using addRowAction view, edit and delete. Everything works fine but I have noticed that on clicking the row not the buttons, the action of the first rowAction button i.e. 'view' in this case is performed. How can I disable it such that only the button click performs the action while clicking anywhere else on the table i.e. on the rows does nothing. I am working on prestashop 1.7.
I searched for the issue and found the solution for that, Hope It will help you
If you want to remove the click you have to define it in your field list for each column with 'remove_onclick' => true,
$this->fields_list = [
'id' => [
'title' => $this->l('Id'),
'type' => 'text',
'align' => 'center',
'search' => false,
'remove_onclick' => true,
],
];
or $helper->no_link = true; in Helper Form
$helper = new HelperList();
$helper->no_link = true;
Try to add "$this->list_no_link = true;" in "__construct()" function.
public function __construct()
{
...
...
$this->list_no_link = true;
}

Call specific tab on edit form in custom module in magento

I created one custom module in magento.When i click on the grid it moves to edit form where i can see three tabs like tab1,tab2,tab3.By default tab1 is selected.Now i want to add one link on grid and when customer click on that link browser redirect user to the tab3.How can i do that.My tab code as follow :
protected function _beforeToHtml()
{
$this->addTab('form_section', array(
'label' => Mage::helper('mymodule')->__('Information'),
'title' => Mage::helper('mymodule')->__('Information'),
'content' => $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tab_form')->toHtml(),
));
$this->addTab('form_section1', array(
'label' => Mage::helper('mymodule')->__(' Management'),
'title' => Mage::helper('mymodule')->__('Management'),
'content' => $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tab_managment')->toHtml(),
));
$this->addTab('form_section2', array(
'label' => Mage::helper('mymodule')->__('Results'),
'title' => Mage::helper('mymodule')->__('Results'),
'content' => $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tab_result')->toHtml(),
));
return parent::_beforeToHtml();
}
My link code like that one on grid listing page. <a class="viewit" href="http://localhost/project/index.php/mymodule/adminhtml_mymodule/view/id/4/key/83063e416ef7f9cfb7825d01e4519293/">View</a>.My contoller function as:
public function viewAction()
{
$this->loadLayout();
$block = $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tab_result');
// $this->_addContent($this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tab_result'))
//->_addLeft($this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tabs'));
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout();
}
The code at Mage_Adminhtml_Block_Widget_Tabs::addTab suggests that tabs have property active. Try adding it to your addTab call:
$this->addTab('form_section2', array(
'label' => Mage::helper('mymodule')->__('Results'),
'title' => Mage::helper('mymodule')->__('Results'),
'content' => $this->getLayout()->createBlock('mymodule/adminhtml_mymodule_edit_tab_result')->toHtml(),
'active' => true
));
Or you can extend your Grid's row URLs with parameter activeTab set to 'form_section2' (the name of the active tab) and add the following code to the _beforeToHtml function of the Tabs block class:
$param = Mage::app()->getRequest()->get('activeTab');
if (array_key_exists($param, $this->_tabs)) {
$this->_tabs[$param]->setActive();
}

Resources