How to ask user for confirmation in Magento 2 console command

#magento2 #snippet

This is a short post showing how to ask user for the confirmation when running Magento 2 console command. The typical use case for this is “Are you sure you want to continue? (y/n)” confirmation which is a good practice if you do not want your command or part of it to be run by accident.


Assuming that you have already created your module and defined the command in di.xml file, here is the example of how to achieve this:

<?php

declare(strict_types=1);

namespace ArchApps\Example\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Framework\Console\QuestionPerformer\YesNo;

class UserInputExample extends Command
{
    private YesNo $questionPerformer;

    /**
     * Defining the questionPerformer class property
     */
    public function __construct(
        YesNo $questionPerformer,
        string $name = null
    ) {
        $this->questionPerformer = $questionPerformer;
        parent::__construct($name);
    }

    /**
     * Bare minimum required to configure the command
     */
    protected function configure()
    {
        $this->setName('archapps:example:user-input-example');
    }

    /**
     * Executes the command and asks for confirmation
     */
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ): int {
        if (!$input->isInteractive()) {
            return Command::FAILURE;
        }

        /**
         * This is the most important part - ask for confirmation
         * If confirmed with yes or y - continue the execution
         */
        $message = ['Are you sure you want to continue (y/n)?'];
        if ($this->questionPerformer->execute($message, $input, $output)) {
            $output->writeln('Success');
            return Command::SUCCESS;
        };

        $output->writeln('failure');
        return Command::FAILURE;
    }
}

Running this command will prompt the user with question “Are you sure you want to continue (y/n)?”, which can only be replied with yes, y, no or n. Entering anything but that shows an error message and the user is repeatedly asked for valid input until such is provided.

"A [y]es or [n]o selection needs to be made. Select and try again."

Make your commands accident-safe! Cheers!

⇐ All Blog Posts
Tweet Share