Symfony2 forms interpret blank strings as nulls

前端 未结 7 2175
温柔的废话
温柔的废话 2021-02-19 09:12

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

相关标签:
7条回答
  • 2021-02-19 09:22

    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.

    0 讨论(0)
  • 2021-02-19 09:22

    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)

    0 讨论(0)
  • 2021-02-19 09:26

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

    0 讨论(0)
  • 2021-02-19 09:33

    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

    0 讨论(0)
  • 2021-02-19 09:33

    In Forms, you can do:

    $builder
    ->add('optionalField', TextType::class, ['required'=>false, 'empty_data'=>''])
    
    0 讨论(0)
  • 2021-02-19 09:39

    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.

    0 讨论(0)
提交回复
热议问题