@@ -940,6 +940,59 @@ These "unmapped fields" can be set and accessed in a controller with::
940
940
Additionally, if there are any fields on the form that aren't included in
941
941
the submitted data, those fields will be explicitly set to ``null ``.
942
942
943
+ Extra fields
944
+ ~~~~~~~~~~~~~~~
945
+
946
+ All form fields are considered properties of the object but you can inject fields
947
+ directly into your view without specifying them in the form definition.
948
+ They can be retrieved via the ``getExtraData `` :class: `Symfony\\ Component\\ Form\\ FormTypeInterface `.
949
+
950
+ This is a creation user form::
951
+
952
+ // ...
953
+ use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
954
+ use Symfony\Component\Form\Extension\Core\Type\SubmitType;
955
+ use Symfony\Component\Form\FormBuilderInterface;
956
+ use App\User;
957
+
958
+ class UserCreateType extends AbstractType
959
+ {
960
+ public function buildForm(FormBuilderInterface $builder, array $options): void
961
+ {
962
+ $builder
963
+ ->add('username', TextType::class)
964
+ ->add('email', EmailType::class)
965
+ ;
966
+ }
967
+
968
+ public function configureOptions(OptionsResolver $resolver)
969
+ {
970
+ $resolver->setDefaults([
971
+ 'data_class' => User::class,
972
+ ]);
973
+ }
974
+ }
975
+
976
+ The extra fields can be injected like this::
977
+
978
+ {# templates/user/create.html.twig #}
979
+ {{ form_start(form) }}
980
+ {{ form_row(form.username) }}
981
+ {{ form_row(form.email) }}
982
+
983
+ {# Hidden field to send additional sponsorship code #}
984
+ <input type="hidden" name="user_create[referralCode]" value="{{ referralCode }}" />
985
+
986
+ <button type="submit">Submit</button>
987
+ {{ form_end(form) }}
988
+
989
+ Here, the sponsorship code is an extra field injected at view level.
990
+
991
+ You can get the referraCode via ``getExtraData ``::
992
+
993
+ $extraData = $form->getExtraData();
994
+ $referraCode = $extraData['referralCode'] ?? null;
995
+
943
996
Learn more
944
997
----------
945
998
0 commit comments