Yii2 button onclick anonymous function

Kimmo from Jyvaskyla picture Kimmo from Jyvaskyla · Jan 13, 2015 · Viewed 28.6k times · Source

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();

Answer

Tahir picture Tahir · Jan 14, 2015

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.