Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

new cookbook article on using empty data for form classes

  • Loading branch information...
commit 9063d674428288d7930c3f8f2ecbeafa9472f43a 1 parent 11b63e3
@joelclermont joelclermont authored
View
1  cookbook/form/index.rst
@@ -11,3 +11,4 @@ Form
create_custom_field_type
create_form_type_extension
use_virtuals_forms
+ use_empty_data
View
47 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());
+ },
+ );
+ }
View
1  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`
View
5 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`
Please sign in to comment.
Something went wrong with that request. Please try again.