Description
The current option "empty_data" is easily misunderstood (see #4715 and #5906). While the option would intuitively set the data that is returned from the field if the field is empty, it in fact sets the view data used if the field is empty, which is then transformed back to model format. So, like mentioned in #5906, setting "empty_data" to an empty string will not lead to the field returning an empty string, because empty strings are transformed to null
by default.
The major use case for "empty_data" is thus to create objects that fields can be mapped into.
Example 1:
$options = array(
'empty_data' => new User();
);
$form = $factory->createBuilder('form', $options)
->add('username', 'text')
->add('password', 'password')
->getForm();
Example 2:
$options = array(
'empty_data' => function (FormInterface $form, $data) {
return new User($data['username']);
}
);
$form = $factory->createBuilder('form', $options)
->add('username', 'text', array('mapped' => false))
->add('password', 'password')
->getForm();
Consequently, I propose to deprecate "empty_data" and rename it to something more intuitive, like "data_constructor":
$options = array(
'data_constructor' => function (FormInterface $form, $data) {
return new User($data['username']);
}
);
$form = $factory->createBuilder('form', $options)
->add('username', 'text', array('mapped' => false))
->add('password', 'password')
->getForm();
We can probably also deprecate the option to pass objects directly to the option instead of closures (see Example 1). IMO objects should be created on demand, not precautiously.
Once the deprecation phase is over (2.3) we can reintroduce "empty_data" with a new meaning and fix #4715 and #5906.