Fabrizio Vanzani

ecommerce development, magento and tech tips

M2: add confirmation in a CLI command

This snippet is useful in case you have a potentially dangerous command and you want to ask for confirmation.
In case of “dry-run” option or “no interaction” mode the command is not stopped.

use Symfony\Component\Console\Question\ConfirmationQuestion;
...
    protected function configure()
    {
       ...
        $this->addOption(
            'dry-run',
            null,
            InputOption::VALUE_NONE,
            'add dry-run to simulate command without saving'
        );
       ...
    }
...
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $isDryRun = $input->getOption('dry-run');
        $noInteraction=$input->getOption('no-interaction');
        if(!$isDryRun && !$noInteraction) {
            $output->writeln('WARNING: this is not a dry run. If you want to do a dry-run, add --dry-run.');
            $question = new ConfirmationQuestion('Are you sure you want to continue? [No] ', false);
            $this->questionHelper = $this->getHelper('question');
            if (!$this->questionHelper->ask($input, $output, $question)) {
                return;
            }
        }
        // proceed ...

    }

Links

https://blog.syncitgroup.com/how-to-add-custom-cli-commands-in-magento2/


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *