From b9e2005cc3e1d1fde6d2f97382a6d37bac14bc8a Mon Sep 17 00:00:00 2001 From: Thomas Landauer Date: Sat, 18 Jan 2025 13:19:11 +0100 Subject: [PATCH 1/2] [Console] Adding associative array Page: https://symfony.com/doc/6.4/components/console/helpers/questionhelper.html#let-the-user-choose-from-a-list-of-answers --- components/console/helpers/questionhelper.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index 2670ec3084a..e8c2d40a470 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -128,7 +128,7 @@ but ``red`` could be set instead (could be more explicit):: $question = new ChoiceQuestion( 'Please select your favorite color (defaults to red)', // choices can also be PHP objects that implement __toString() method - ['red', 'blue', 'yellow'], + ['red', 'blue', 'yellow'], // pass an associative array to display custom indices: [3 => 'red', 7 => 'blue'] 0 ); $question->setErrorMessage('Color %s is invalid.'); From 53b7a44f7afabbe9b9502cb48ff1971d776689f9 Mon Sep 17 00:00:00 2001 From: Javier Eguiluz Date: Tue, 21 Jan 2025 09:52:45 +0100 Subject: [PATCH 2/2] Reword --- components/console/helpers/questionhelper.rst | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index e8c2d40a470..3dc97d5c0d3 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -128,7 +128,7 @@ but ``red`` could be set instead (could be more explicit):: $question = new ChoiceQuestion( 'Please select your favorite color (defaults to red)', // choices can also be PHP objects that implement __toString() method - ['red', 'blue', 'yellow'], // pass an associative array to display custom indices: [3 => 'red', 7 => 'blue'] + ['red', 'blue', 'yellow'], 0 ); $question->setErrorMessage('Color %s is invalid.'); @@ -145,6 +145,28 @@ The option which should be selected by default is provided with the third argument of the constructor. The default is ``null``, which means that no option is the default one. +Choice questions display both the choice value and a numeric index, which starts +from 0 by default. The user can type either the numeric index or the choice value +to make a selection: + +.. code-block:: terminal + + Please select your favorite color (defaults to red): + [0] red + [1] blue + [2] yellow + > + +.. tip:: + + To use custom indices, pass an array with custom numeric keys as the choice + values:: + + new ChoiceQuestion('Select a room:', [ + 102 => 'Room Foo', + 213 => 'Room Bar', + ]); + If the user enters an invalid string, an error message is shown and the user is asked to provide the answer another time, until they enter a valid string or reach the maximum number of attempts. The default value for the maximum number