Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 forms interpret blank strings as nulls

Tags:

symfony

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 some text in it, but when the field is left blank, I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'recap' cannot be null

That's right - the column recap can't be null. I set it that way on purpose. Null means unknown. When the user leaves recap blank, the value of recap is not unknown; it's blank.

My question is how to get Symfony to save recap as '' when it's blank, not null.

like image 994
Jason Swett Avatar asked Mar 29 '12 15:03

Jason Swett


People also ask

Is empty string treated as null?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .

Is null better than empty string?

The concept of NULL and empty string often creates confusion since many people think NULL is the same as a MySQL empty string. However, this is not the case. An empty string is a string instance of zero length. However, a NULL has no value at all.

What is null to string?

“A null String is Java is literally equal to a reserved word “null”. It means the String that does not point to any physical address.” In Java programming language, a “null” String is used to refer to nothing. It also indicates that the String variable is not actually tied to any memory location.


1 Answers

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.

like image 74
René Höhle Avatar answered Sep 21 '22 19:09

René Höhle