New in Symfony 2.2: Autocomplete on the Command Line
January 9, 2013 • Published by Fabien Potencier
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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!
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.