diff --git a/forms.rst b/forms.rst index 4c0485947e..7f2fc0dead 100644 --- a/forms.rst +++ b/forms.rst @@ -950,12 +950,11 @@ the submitted data, those fields will be explicitly set to ``null``. Extra fields ~~~~~~~~~~~~ -All form fields are considered properties of the object but you can inject -fields directly into your view without specifying them in the form definition. -They can be retrieved via the :method:`FormInterface::getExtraData() ` -method. +By default, Symfony expects every submitted field to be defined in the form. Any +additional submitted fields are treated as "extra fields". You can access them via the +:method:`FormInterface::getExtraData() ` method. -This is a creation user form:: +For example, consider a user creation form:: // ... use App\User; @@ -981,7 +980,8 @@ This is a creation user form:: } } -The extra fields can be injected like this: +You can render an additional input in the template without adding it to the form +definition: .. code-block:: html+twig @@ -990,20 +990,22 @@ The extra fields can be injected like this: {{ form_row(form.username) }} {{ form_row(form.email) }} - {# Hidden field to send additional referral code #} + {# hidden field to send an additional referral code #} {{ form_end(form) }} -Here, the referral code is an extra field injected at view level. - -You can get the referral code via ``getExtraData``:: +In this example, ``referralCode`` is submitted as an extra field and you can +read it like this:: $extraData = $form->getExtraData(); $referralCode = $extraData['referralCode'] ?? null; - -> Don't forget to set :ref:`allow_extra_fields ` option to ``true`` on your form + +.. note:: + + To accept extra fields, set the :ref:`allow_extra_fields ` + option to ``true``. Otherwise, the form will be invalid. Learn more ----------