Yii2 button onclick anonymous function - javascript

I am new to Yii2, and I am struggling to trigger an anonymous function by pressing a Yii2 button.
Below are 6 samples, of which first two are OK.
But that is not exactly what I wish to have.
I would like to know how I can get an anonymous function working, like cases for "Button 3" and "Button 5". I tested how to make a function call via Controller, and that works ok, but that is neither what I want. I would appreciate Your help - thanks!
// This works
$button1 = Button::begin (
[
'label' => 'Button 1',
'options' => [
'class' => 'btn btn-primary',
'onclick' => 'alert("Button 1 clicked");',
],
]);
$button1->run();
// This works
echo Html::button('Button 2', [ 'class' => 'btn btn-primary', 'onclick' => 'alert("Button 2 clicked");' ]);
// This DOES NOT work
echo Html::button('Button 3', [ 'class' => 'btn btn-primary', 'onclick' => 'function ( $event ) { alert("Button 3 clicked"); }' ]);
// This DOES NOT work
$button4 = Button::begin (
[
'label' => 'Button 4',
'options' => [
'class' => 'btn btn-primary',
// 'onclick' => 'alert("Button 1 clicked");',
],
]);
$button4->on('onclick', 'alert("Button 4 clicked");' );
$button4->run();
// This DOES NOT work
$button5 = Button::begin (
[
'label' => 'Button 5',
'options' => [
'class' => 'btn btn-primary',
'onclick' => 'function ( $event ) { alert("Button 5 clicked"); }',
],
]);
$button5->run();
// This DOES NOT work
$button6 = Button::begin (
[
'label' => 'Button 6',
'options' => [
'class' => 'btn btn-primary',
//'onclick' => 'function ( $event ) { alert("Button 4 clicked"); }',
],
]);
$button6->on('onclick', 'function ( $event ) { alert("Button 6 clicked"); }' );
$button6->run();

You can wrap your anonymous function in self-executing anonymous function ()().
So your second example would look something like this.
echo Html::button('Button 3', [ 'class' => 'btn btn-primary', 'onclick' => '(function ( $event ) { alert("Button 3 clicked"); })();' ]);
Search Google to learn more about self-executing anonymous functions in Javascript. You should find tons of information and examples.

You can try something like using a submitButton instead of a button,
if you have other submitButton insert a condition that is for example 0 when you use the first button and 1 when you use the second one, then put your function in the controller and check, the first submit launches the function, the second submit makes something else. I know is not the best way, but it is the only way I imagine to do that.
Or, you can use ajaxSubmitButton:
AjaxSubmitButton::begin([
'label' => 'Check',
'ajaxOptions' => [
'type' => 'POST',
'url' => 'country/getinfo',
/*'cache' => false,*/
'success' => new \yii\web\JsExpression('function(html){
$("#output").html(html);
}'),
],
'options' => [
'class' => 'customclass',
'type' => 'submit'
]
]);

Related

Trigger tab click event via button

How can I trigger click on 2nd tab event via butto, with jquery?
$('#packingGrid2').trigger('click');
I tried do this with trigger pasted above, but it doesnt work. Any thoughts?
#Keydose, there is my code.
$items = [
[
'url' => \Yii::$app->params['pjax_enabled']?null:Url::to(['step_1', 'tab' => 'packingGrid1']),
'label' => '<i class="glyphicon glyphicon-check"></i> Weryfikacja linii',
'content' => \Yii::$app->controller->renderPartial('step_1', [
'gridId' => 'packingGrid1',
'model' => $model,
'form' => $form,
]),
'linkOptions' => [
'data-id' => 'packingGrid1',
],
],
[
'url' => \Yii::$app->params['pjax_enabled']?null:Url::to(['step_2', 'tab' => 'packingGrid2']),
'label' => '<i class="glyphicon glyphicon-user"></i> Ustawienia pracowników',
'content' => ($model->isNewRecord) ? '<strong>Uzupełnij weryfikację linii</strong>' :
\Yii::$app->controller->renderPartial('step_2', [
'gridId' => 'packingGrid2',
'model' => $model,
'form' => $form,
]),
'linkOptions' => [
'data-id' => 'packingGrid2',
],
'active' => ($model->isNewRecord) ? false : true,
],
],
];
echo TabsX::widget([
'items' => $items,
'position' => TabsX::POS_ABOVE,
'encodeLabels'=>false,
'bordered'=>true,
]);

Yii2: window.open from PHP

I have a GridView of a index view with some columns. I added a print button that link to a URL that has to be opened in a new window.
This code work but the URL is not open in a new window.
'columns' => [
'column1',
'column2',
'column3',
'column4',
'column5',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{download} {update} {delete}',
'buttons' => [
'download' => function ($url, $model) {
return Html::a(
'<span class="fa fa-print"></span>',
'/disposicion-licencia/print-estival?id=' . $model->id,
[
'title' => 'Download',
'data-pjax' => '0',
]
);
},
],
],
]
I think I need JavaScript code like this:
window.open('/disposicion-licencia/print-estival?id=$id');
But I don't know where to use it.
For a new window you need 'target' => '_blank':
return Html::a(
'<span class="fa fa-print" ></span>',
'/disposicion-licencia/print-estival?id=' . $model->id,
[
'title' => 'Download',
'data-pjax' => '0',
'target' => '_blank',
]
);

yii2 kartik switch input type radio button get value in javascript

I use the yii2 kartik switch input with the type radio and i want to get the value of the selected option in javascript (specially in a JsExpression), here is my code :
$model->orientation = 'Portrait';
echo $form->field($model, 'orientation')->widget(SwitchInput::classname(), [
'name' => 'information_orientation',
'type' => SwitchInput::RADIO,
'value' => 'Portrait',
'items' => [
['label' => 'Portrait&nbsp&nbsp&nbsp', 'value' => 'Portrait'],
['label' => 'Paysage&nbsp&nbsp&nbsp', 'value' => 'Paysage'],
],
'pluginOptions' => [
'onText' => 'Oui',
'offText' => 'Non',
'onColor' => 'success',
'offColor' => 'danger',
'size' => 'mini'
],
'labelOptions' => ['style' => 'font-size: 13px'],
]);
I have tried :
$([name='information-orientation']).val()
But it returned an undifined value
SwitchInput class does not care about the name property you give it
according to their docs, you need to wrap name in a options array
echo $form->field($model, 'orientation')
->widget(SwitchInput::classname(), [
'options' => ['name' => 'information_orientation'],
'type' => SwitchInput::RADIO,
....
from docs:
options: array the HTML attributes for the widget input tag.
edit:
you can then use the following
// to get value:
$("[name='information_orientation']").val()
// to check if the switch is or on off
$("[name='information_orientation']").prop('checked')

How can I use callback use x-editable like yii extension

I try use callback. If data success update then i need to display modal window. But its not working! Help please! I dont know, how it works. Write me please.
In View
<?php
$this->widget('editable.EditableField', array(
'type' => 'select',
'params' => array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'model' => $model,
'attribute' => 'category_id',
'url' => $this->createUrl('course/updateSameInfo'),
'source' => Editable::source(Coursecat::model()->findAll(), 'id', 'name'),
'placement' => 'right',
));
?>
In Controller
public function actionUpdateSameInfo()
{
$es = new EditableSaver('Course'); //'User' is name of model to be updated
$es->update();
}
Use success property. Here is the documentation http://x-editable.demopage.ru/index.php?r=site/widgets#Options
Try this
<?php
$this->widget('editable.EditableField', array(
'type' => 'select',
'params' => array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'model' => $model,
'attribute' => 'category_id',
'url' => $this->createUrl('course/updateSameInfo'),
'source' => Editable::source(Coursecat::model()->findAll(), 'id', 'name'),
'placement' => 'right',
'success' => 'js: function(response, newValue) {
console.log(response); //Open the browser console to check the data
}'
));
?>

Yii ajaxSubmitButton client-side validation issue

As you probably know, Yii does not perform client-side validation with CHtml::ajaxSubmitButton. So after a long time spending on google and stackoverflow, I found that I should use the following link
a-simple-way-to-get-yii-client-side-form-validation-run-when-submitting-by-ajax
Now, It can perform client-side validation. But, the success or complete ajax functions does not fire after validation.
Any Idea?
To be more familiar with topic, I put my codes here:
Yii::app()->clientScript->registerCoreScript('yii');
Yii::app()->clientScript->registerScript('Yii Fix',";$.yii.fix = {
ajaxSubmit : {
beforeSend : function(form) {
return function(xhr,opt) {
form = $(form);
$._data(form[0], 'events').submit[0].handler();
var he = form.data('hasError');
form.removeData('hasError');
return he===false;
}
},
afterValidate : function(form, data, hasError) {
$(form).data('hasError', hasError);
return true;
}
}
};",CclientScript::POS_HEAD);
My form:
$uniqid = uniqid();
$form = $this->beginWidget('CActiveForm', array(
'id' => 'pagescontents-add-new-contents'.$uniqid,
'htmlOptions' => array(
'class' => 'form-horizontal',
'role' => 'form'
),
'enableClientValidation' => true,
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>false,
'afterValidate'=>'js:$.yii.fix.ajaxSubmit.afterValidate',
),
));
//The rest of code
...
//Ajax submit button
$button_uniqid = uniqid();
echo CHtml::ajaxSubmitButton(Messages::getMessage('ADD_NEW'), $this->createUrl('pagescontents/addPage/'), array(
'beforeSend' => '$.yii.fix.ajaxSubmit.beforeSend("#pagescontents-add-new-contents'.$uniqid.'")',
'type'=>'POST',
'success' => "js:function(data){
$('#page_modal').html('');
$('.modal-backdrop').remove();
$('#pageContents_list').html(data);
}",
),
array(
'class' => 'btn btn-primary',
// 'data-dismiss' => 'modal',
'id' => 'deletesubmit_' . $button_uniqid
)
);
I try your code and find that if you remove the line "'enableAjaxValidation'=>true," your code will work perfectly please check it and let me know that is work for you too or not.

Categories

Resources