Contributed by
Lee McDermott
in #6391 and #6564.

Last month, I talked about some of the enhancements we made to the Console component for 2.2. Today, I want to show you another amazing enhancement: autocompletion on the command line!

The code to make it happen is very similar to the code you are already using when asking a question from within a command:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

$app = new Application();
$app->register('ask-color')->setCode(function (InputInterface $input, OutputInterface $output) use ($app) {
    $colors = array('red', 'blue', 'yellow', 'yellow-light', 'yellow-dark');
    $validation = function ($color) use ($colors) {
        if (!in_array($color, array_values($colors))) {
            throw new \InvalidArgumentException(sprintf('Color "%s" is invalid.', $color));
        }

        return $color;
    };

    // ask and validate the answer
    $dialog = $app->getHelperSet()->get('dialog');
    $color = $dialog->askAndValidate($output, 'Enter your favorite color (default to red): ', $validation, false, 'red', $colors);

    $output->writeln(sprintf('You have just entered: %s', $color));
});

$app->run();

The only difference is that you can now pass all valid answers as the last argument to the askAndValidate() method, and that changes everything. Here is a small video that demonstrates how the command behaves:


Using tabs and arrows, you can now type the right answer faster, without any possible typos! And it even works on Windows!