|
| 1 | +.. index:: |
| 2 | + single: Form; Empty data |
| 3 | + |
| 4 | +How to configure Empty Data for a Form Class |
| 5 | +============================================ |
| 6 | + |
| 7 | +The ``empty_data`` option allows you to specify an empty data set for your |
| 8 | +form class. This empty data set would be used if you bind your form, but |
| 9 | +haven't yet called ``setData()``. |
| 10 | + |
| 11 | +By default, ``empty_data`` is set to ``null``. Or, if you have specified |
| 12 | +a ``data_class`` option for your form class, it will default to a new instance |
| 13 | +of that class. That instance will be created by calling the constructor |
| 14 | +with no arguments. |
| 15 | + |
| 16 | +If you want to override this default behavior, there are two ways to do this. |
| 17 | + |
| 18 | +Option 1: Instantiate a new Class |
| 19 | +--------------------------------- |
| 20 | + |
| 21 | +One reason you might use this option is if you want to use a constructor |
| 22 | +that takes arguments. Remember, the default ``data_class`` option calls |
| 23 | +that constructor with no arguments:: |
| 24 | + |
| 25 | + public function getDefaultOptions() |
| 26 | + { |
| 27 | + return array( |
| 28 | + 'empty_data' => new User($this->someDependency), |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | +Option 2: Provide a Closure |
| 33 | +--------------------------- |
| 34 | + |
| 35 | +Using a closure is the preferred method, since it will only create the object |
| 36 | +if it is needed. |
| 37 | + |
| 38 | +The closure must accept a ``FormInterface`` instance as the first argument:: |
| 39 | + |
| 40 | + public function getDefaultOptions() |
| 41 | + { |
| 42 | + return array( |
| 43 | + 'empty_data' => function (FormInterface $form) { |
| 44 | + return new User($form->get('username')->getData()); |
| 45 | + }, |
| 46 | + ); |
| 47 | + } |
0 commit comments