8000 minor #7125 Add docs about console question answer normalizing. (Spac… · a-ast/symfony-docs@b5587f0 · GitHub
[go: up one dir, main page]

Skip to content

Commit b5587f0

Browse files
committed
minor symfony#7125 Add docs about console question answer normalizing. (SpacePossum, javiereguiluz)
This PR was submitted for the 2.8 branch but it was merged into the 2.7 branch instead (closes symfony#7125). Discussion ---------- Add docs about console question answer normalizing. Add description about how to use normalizing on an answer given on a question in a console application. Commits ------- 5e39973 Minor rewords in the text and the code example 2cae22f Update questionhelper.rst 5f81796 Add docs about console question answer normalizing.
2 parents c698051 + 5e39973 commit b5587f0

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

components/console/helpers/questionhelper.rst

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,38 @@ convenient for passwords::
209209
like in the example above. In this case, a ``RuntimeException``
210210
would be thrown.
211211

212+
Normalizing the Answer
213+
----------------------
214+
215+
Before validating the answer, you can "normalize" it to fix minor errors or
216+
tweak it as needed. For instance, in a previous example you asked for the bundle
217+
name. In case the user adds white spaces around the name by mistake, you can
218+
trim the name before validating it. To do so, configure a normalizer using the
219+
:method:`Symfony\\Component\\Console\\Question\\Question::setNormalizer`
220+
method::
221+
222+
use Symfony\Component\Console\Question\Question;
223+
224+
// ...
225+
public function execute(InputInterface $input, OutputInterface $output)
226+
{
227+
// ...
228+
$question = new Question('Please enter the name of the bundle', 'AppBundle');
229+
$question->setNormalizer(function ($value) {
230+
// $value can be null here
231+
return $value ? trim($value) : '';
232+
});
233+
234+
$name = $helper->ask($input, $output, $question);
235+
}
236+
237+
238+
.. caution::
239+
240+
The normalizer is called first and the returned value is used as the input
241+
of the validator. If the answer is invalid, don't throw exceptions in the
242+
normalizer and let the validator handle those errors.
243+
212244
Validating the Answer
213245
---------------------
214246

@@ -226,11 +258,12 @@ method::
226258
// ...
227259
$question = new Question('Please enter the name of the bundle', 'AcmeDemoBundle');
228260
$question->setValidator(function ($answer) {
229-
if ('Bundle' !== substr($answer, -6)) {
261+
if (!is_string($answer) || 'Bundle' !== substr($answer, -6)) {
230262
throw new \RuntimeException(
231263
'The name of the bundle should be suffixed with \'Bundle\''
232264
);
233265
}
266+
234267
return $answer;
235268
});
236269
$question->setMaxAttempts(2);

0 commit comments

Comments
 (0)
0