I have a Symfony2 form with a variety of fields, including one optional text field called recap
.
This recap
field saves perfectly when there\'s
I have another solution for this issue:
create dummy class
class EmptyString {
public function __toString() {
return '';
}
}
and set
$builder->add('recap', 'text', [
'empty_data' => new EmptyString(),
]);
When entity will be stored to DB, it will automatically converted to empty string.
I also came across this problem. And an elegant solution was suggested to me was: to make this definition @ORM\Column(type="string", length=50, nullable=true)
True, lost many hours on it ;-( the "transformation" is hardcoded in component Form.php line 1113 !
private function viewToNorm($value)
{
$transformers = $this->config->getViewTransformers();
if (!$transformers) {
return '' === $value ? null : $value;
}
for ($i = count($transformers) - 1; $i >= 0; --$i) {
$value = $transformers[$i]->reverseTransform($value);
}
return $value;
}
In my opinion, its a big error (because is the role of DataTransformer, not Form). So the solution is to create your own DataTransformer and associate it to the text type. Currently I am losing so much time with Symfony2, always seeking in the sources these kind of little hack ;-(
I think you're taking the problem the wrong way: when the user leaves recap blank the value is unknown because not provided . For example you don't say that an empty birthdate field means that birthdate is equaled to '' but that birthdate is unknown. Same goes for addresss, etc...
So if your user isn't required to fill this field then it seems that the most relevant response is in fact to set your field as being nullable
In Forms, you can do:
$builder
->add('optionalField', TextType::class, ['required'=>false, 'empty_data'=>''])
Go to your Entity and go to the declaration of the variables.
/**
* @var string $name
*
* @ORM\Column(type="string", length=50)
*/
public $recap = '';
you can assign a default value for $recap.
Or otherway when you have the function setRecap you can check if empty or not set and set the value you expect.
public function setRecap($recap) {
$this->recap = !isset($recap) ? '': $recap;
}
Or you set the default Value in your form Type to '' but i think then its not what you expect.