Yii2 onclick button anonymous function

I am new to Yii2 and I am trying to call an anonymous function by pressing the Yii2 button. Below are 6 samples, of which the first two are in order. But this is not exactly what I want. I would like to know how I can work with an anonymous function, for example, for the buttons "Button 3" and "Button 5". I tested how to make a function call through a controller, and this works fine, but that is not what I want. I would be grateful for 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(); 
+5
source share
2 answers

You can wrap your anonymous function in a self-signed anonymous function ()() .

So your second example will 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 a ton of information and examples.

+8
source

You can try something like using submitButton instead of a button, if you have another SubmitButton, insert a condition that, for example, 0 when you use the first button and 1 when you use the second, then put your function in the controller and check , the first serve starts the function, the second serve does the rest. I know that this is not the best way, but this is the only way I imagine it.

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' ] ]); 
0
source

Source: https://habr.com/ru/post/1210964/


All Articles