8

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.

3 Answers 3

9

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")
      }
      ...
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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, ...);

Comments

0

You can use the method prompt() provided in the yii\console\Controller that calls the yii\helpers\BaseConsole::prompt() and gives you additional control to validate the input too after the user enters or just mark it as required so that it is not empty

$code = $this->prompt(
    'Enter 4-Chars-Pin',
    [
        'required' => true,
        'validator' => function ($input, &$error) {
            if (strlen($input) !== 4) {
                $error = 'The Pin must be exactly 4 chars!';
                return false;
            }
            return true;
        },
    ]
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.