Hpatoio
Hpatoio

Reputation: 1815

Empty text field set to null in symfony2 form

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 ?

Upvotes: 3

Views: 5912

Answers (2)

Michas
Michas

Reputation: 9428

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

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

Upvotes: 2

sjagr
sjagr

Reputation: 16502

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;
}

Upvotes: 4

Related Questions