Skip to content

Commit 87c0536

Browse files
committed
[#2415] Proofreading great new empty_data document and expanding some of the examples
1 parent e93ccf1 commit 87c0536

File tree

1 file changed

+43
-6
lines changed

1 file changed

+43
-6
lines changed

cookbook/form/use_empty_data.rst

Lines changed: 43 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,19 @@ How to configure Empty Data for a Form Class
66

77
The ``empty_data`` option allows you to specify an empty data set for your
88
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+
}
1022

1123
By default, ``empty_data`` is set to ``null``. Or, if you have specified
1224
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
2234
that takes arguments. Remember, the default ``data_class`` option calls
2335
that constructor with no arguments::
2436

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
2644
{
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+
}
3059
}
3160

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+
3266
Option 2: Provide a Closure
3367
---------------------------
3468

@@ -37,11 +71,14 @@ if it is needed.
3771

3872
The closure must accept a ``FormInterface`` instance as the first argument::
3973

74+
use Symfony\Component\Form\FormInterface;
75+
// ...
76+
4077
public function getDefaultOptions()
4178
{
4279
return array(
4380
'empty_data' => function (FormInterface $form) {
44-
return new User($form->get('username')->getData());
81+
return new Blog($form->get('title')->getData());
4582
},
4683
);
4784
}

0 commit comments

Comments
 (0)