3

I've a form with a text field. This field maps to a not nullable field in my DB (is a legacy DB and I can't change this)

The problem is that Symfony2 always set empty text field to NULL and, this make the insert fails.

Is there a way to tell Symfony2 to not set empty text fields to NULL ?

2
  • set it in the entity for example * @ORM\Column(name="address", type="string", length=255, nullable=true) Commented Feb 17, 2015 at 16:39
  • @hous: I want to insert empty string, not null. Commented Feb 17, 2015 at 16:49

2 Answers 2

4

Start by setting a blank value by default in the entity

/**
 * @ORM\Column(name="example", type="string", length=255, nullable=false)
 */
private $example = '';

As for your issue, unfortunately you are describing a known issue/bug with Symfony, so you'll have to override the value being set to the setter function:

public function setExample($example = null) {
    if (empty($example)) {
        $example = '';
    }
    $this->example = $example;
}
Sign up to request clarification or add additional context in comments.

6 Comments

I've tried this already but doesn't work ! Symfony sets empty strings to null
Yes. Things works that way. But is see it as an hack/workaround. I would like Symfony to not set the field to null. I've changed you example. Please accept it.
@Hpatoio I'd be cautious about using a direct type comparison in case $example is false or some other empty value, or else Symfony may send a null value to the database again. I'm going to reference a known bug in an edit.
I didn't know about that bug. BTW, I don't think your code fix this the problem. If Symfony calls somewhere $myEntity->setExample(null) I still get null in my DB. And this is what I don't want. Do you agree ?
@Hpatoio Please leave the answer as-is, it's meant to also help other readers that may end up on your question. If you remove the = null portion from the method declaration, you will get errors if you try to use $entity->setExample() without a value (which is supposed to be a valid call for setting an empty value.) empty() works better than is_null() because it accounts for false, null, and 0 - all of which values could be (but not necessarily will be) typecasted into null when being stored into the database.
|
2

The code below works for me. I tune the form definition.

    $builder->add('comment', TextareaType::class, [
        'empty_data'    => '',
        'required'      => false,
    ]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.