Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take user input in Yii2 console command

Tags:

php

yii2

I want to create a console command in Yii2 where I can take the input from the user.

I have looked into the Yii2 documentation here-

http://www.yiiframework.com/doc-2.0/guide-tutorial-console.html

But I could not find anything helpful.

I have also searched on Google and StackOverflow with no luck.

like image 534
Pankaj Avatar asked Jul 22 '17 05:07

Pankaj


2 Answers

CLI command prompt for any user string:

class CronController extends yii\console\Controller
{
   public function actionSendTestmail()
   {
      $emailTo = \yii\helpers\BaseConsole::input("Recipient email: ");
      ...
   }
}

or just ask for confirmation [yes|no]:

class CronController extends yii\console\Controller
{
   public function actionSendTestmail()
   {
      $emailTo = Yii::$app->params["email.to"];
      if(!$this->confirm("Send email to {$emailTo}?")){
         exit("Sending email interrupted.\n")
      }
      ...
   }
}
like image 96
lubosdz Avatar answered Oct 11 '22 13:10

lubosdz


Check out yii\helpers\BaseConsole helper class method input().

input('Enter your name');

Will prompt you for your name.

Or you can define arguments for the action method to pass values to the action.

static function actionDoSomething (arg1, arg2, ...);
like image 40
Barry Avatar answered Oct 11 '22 12:10

Barry