Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine/Symfony "translates" empty string into a NULL

So there is a form, and non-required fields, like say "first_name". When I leave this field empty, I got an error that "Column 'first_name' cannot be null", because indeed it can't. But why does Doctrine converts empty string to NULL?

But I have to questions regarding this:

  1. Is this possible to disable it?

  2. What's your opinion about it? Until now I was used to the fact that when a form field was empty, I simply inserted an empty string. Not NULL o_O But... somebody told me this is a principle we should follow. For me however, NULL means "there is no value", and '' (empty string) means something different - "there IS a value, but it's empty". What do you think?

p.s. I use MySql if it matters.

edit:

there is a similar question:

Symfony2 forms interpret blank strings as nulls but maybe there is a new solution as of 2016?

The only solution which work is the one from the accepted answer:

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) {
  if(!isset($recap)) {
    $this->recap = ''
  } else {
    $this->recap = $recap;
  }
}

But I have a lot of such fields, and this seems overkill to me, there must a simpler solution.

p.s. I did not try Thomas Decaux' answer below the accepted answer, because it seems hacky to me.

like image 490
konrad_firm Avatar asked Dec 18 '25 06:12

konrad_firm


1 Answers

Well, as somebody suggested me, it's as simple as:

public function setUserName($userName) {
    $this->userName = (string)$userName;
    return $this;
}

In an entity.

Edit: plus, we need to give a default value for the variable, like:

$userName = '';
like image 103
konrad_firm Avatar answered Dec 20 '25 20:12

konrad_firm