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:



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;

     * Bare minimum required to configure the command
    protected function configure()

     * 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)) {
            return Command::SUCCESS;

        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