Search code examples
yii2yii2-basic-app

(Yii2) submitButton =>Converting onclick function to siteControllers?


index.php

<?php  use yii\helpers\Html; ?>

<?= Html::submitButton('tew',

['class' => 'btn btn-primary',

'onClick'=>'buttonClicked']) ?>

siteController.php

public function actionIndex()
    {
        if($buttonClicked)
           {

        echo "Button Clicked";

}
        return $this->render('index');

So how to call button click function in siteContoller


Solution

  • If you need check a specific submit button you must name it and assign a value You can obtain the submit this way

     'value'=>'create_add', 'name'=>'submit'
        <?= Html::submitButton('tew',['class' => 'btn btn-primary', 
                'value'=>'my_value', 'name'=>'submit',
              'onClick'=>'buttonClicked']) ?>
    

    then in your controller you can check the if specific button is clicked

    public function actionIndex()
    {
       if (Yii::$app->request->post('submit')==='my_value') {
          echo "Button my_value Clicked";
       } 
       return $this->render('index');
    }
    

    In your case you must add the value

    <?php  
    
    use yii\helpers\Html; 
    
    ?>
    
    <?= Html::submitButton('tew',['class' => 'btn btn-primary', 
                    'value' => 'my_value', // you must add  a proper value to check in action 
                    'onClick'=>'buttonClicked']) ?>