Archives
Master Symfony2 fundamentals
Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).
trainings.sensiolabs.com
Symfony hosting done right
ServerGrove, outstanding support at the right price for your Symfony hosting needs.
servergrove.com
Discover the SensioLabs Support
Access to the SensioLabs Competency Center for an exclusive and tailor-made support on Symfony
sensiolabs.com
Blog
New in Symfony 2.2: Autocomplete on the Command Line
by
Fabien Potencier
– January 09, 2013
– 9 comments
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!





is a trademark of Fabien Potencier. All rights reserved.
Add a Comment
Comments