diff --git a/cookbook/form/index.rst b/cookbook/form/index.rst index 337f411dd09..75d90cc99be 100644 --- a/cookbook/form/index.rst +++ b/cookbook/form/index.rst @@ -11,3 +11,4 @@ Form create_custom_field_type create_form_type_extension use_virtuals_forms + use_empty_data diff --git a/cookbook/form/use_empty_data.rst b/cookbook/form/use_empty_data.rst new file mode 100644 index 00000000000..3ca80b35ee0 --- /dev/null +++ b/cookbook/form/use_empty_data.rst @@ -0,0 +1,47 @@ +.. index:: + single: Form; Empty data + +How to configure Empty Data for a Form Class +============================================ + +The ``empty_data`` option allows you to specify an empty data set for your +form class. This empty data set would be used if you bind your form, but +haven't yet called ``setData()``. + +By default, ``empty_data`` is set to ``null``. Or, if you have specified +a ``data_class`` option for your form class, it will default to a new instance +of that class. That instance will be created by calling the constructor +with no arguments. + +If you want to override this default behavior, there are two ways to do this. + +Option 1: Instantiate a new Class +--------------------------------- + +One reason you might use this option is if you want to use a constructor +that takes arguments. Remember, the default ``data_class`` option calls +that constructor with no arguments:: + + public function getDefaultOptions() + { + return array( + 'empty_data' => new User($this->someDependency), + ); + } + +Option 2: Provide a Closure +--------------------------- + +Using a closure is the preferred method, since it will only create the object +if it is needed. + +The closure must accept a ``FormInterface`` instance as the first argument:: + + public function getDefaultOptions() + { + return array( + 'empty_data' => function (FormInterface $form) { + return new User($form->get('username')->getData()); + }, + ); + } diff --git a/cookbook/map.rst.inc b/cookbook/map.rst.inc index bf372309ff9..3668c2d5557 100644 --- a/cookbook/map.rst.inc +++ b/cookbook/map.rst.inc @@ -80,6 +80,7 @@ * :doc:`/cookbook/form/create_custom_field_type` * :doc:`/cookbook/form/create_form_type_extension` * :doc:`/cookbook/form/use_virtuals_forms` + * :doc:`/cookbook/form/use_empty_data` * (validation) :doc:`/cookbook/validation/custom_constraint` * (doctrine) :doc:`/cookbook/doctrine/file_uploads` diff --git a/reference/forms/types/options/empty_data.rst.inc b/reference/forms/types/options/empty_data.rst.inc index 1827d560b4b..685de954a2a 100644 --- a/reference/forms/types/options/empty_data.rst.inc +++ b/reference/forms/types/options/empty_data.rst.inc @@ -20,3 +20,8 @@ value is selected, you can do it like this: 'empty_value' => 'Choose your gender', 'empty_data' => null )); + +.. note:: + + If you want to set the ``empty_data`` option for your entire form class, + see the cookbook article :doc:`/cookbook/form/use_empty_data`