@@ -6,7 +6,19 @@ How to configure Empty Data for a Form Class
6
6
7
7
The ``empty_data `` option allows you to specify an empty data set for your
8
8
form class. This empty data set would be used if you bind your form, but
9
- haven't yet called ``setData() ``.
9
+ haven't called ``setData() `` on your form or passed in data when you created
10
+ you form. For example::
11
+
12
+ public function indexAction()
13
+ {
14
+ $blog = // ...
15
+
16
+ // $blog is passed in as the data, so the empty_data option is not needed
17
+ $form = $this->createForm(new BlogType(), $blog);
18
+
19
+ // no data is passed in, so empty_data is used to get the "starting data"
20
+ $form = $this->createForm(new BlogType());
21
+ }
10
22
11
23
By default, ``empty_data `` is set to ``null ``. Or, if you have specified
12
24
a ``data_class `` option for your form class, it will default to a new instance
@@ -22,13 +34,35 @@ One reason you might use this option is if you want to use a constructor
22
34
that takes arguments. Remember, the default ``data_class `` option calls
23
35
that constructor with no arguments::
24
36
25
- public function getDefaultOptions()
37
+ // src/Acme/DemoBundle/Form/Type/BlogType.php
38
+ // ...
39
+
40
+ use Symfony\Component\Form\AbstractType;
41
+ use Acme\DemoBundle\Entity\Blog;
42
+
43
+ class BlogType extends AbstractType
26
44
{
27
- return array(
28
- 'empty_data' => new User($this->someDependency),
29
- );
45
+ private $someDependency;
46
+
47
+ public function __construct($someDependency)
48
+ {
49
+ $this->someDependency = $someDependency;
50
+ }
51
+ // ...
52
+
53
+ public function getDefaultOptions()
54
+ {
55
+ return array(
56
+ 'empty_data' => new Blog($this->someDependency),
57
+ );
58
+ }
30
59
}
31
60
61
+ You can instantiate your class however you want. In this example, we pass
62
+ some dependency into the ``BlogType `` when we instantiate it, then use that
63
+ to instantiate the ``Blog `` object. The point is, you can set ``empty_data ``
64
+ to the exact "new" object that you want to use.
65
+
32
66
Option 2: Provide a Closure
33
67
---------------------------
34
68
@@ -37,11 +71,14 @@ if it is needed.
37
71
38
72
The closure must accept a ``FormInterface `` instance as the first argument::
39
73
74
+ use Symfony\Component\Form\FormInterface;
75
+ // ...
76
+
40
77
public function getDefaultOptions()
41
78
{
42
79
return array(
43
80
'empty_data' => function (FormInterface $form) {
44
- return new User ($form->get('username ')->getData());
81
+ return new Blog ($form->get('title ')->getData());
45
82
},
46
83
);
47
84
}
0 commit comments