Symfony3: How to update boolean to false using PATCH method

后端 未结 3 847
一个人的身影
一个人的身影 2021-01-18 09:20

I have a big entity and a big form. When updating my entity, I only render parts of my form, through ajax calls. On client side, I\'m using Jquery and html5 FormData

3条回答
  •  渐次进展
    2021-01-18 09:44

    Here goes a working solution, that could be improved.

    To force unchecked checkboxes to appear in the request, thanks to Felix Kling's comment on this question, I've added this js before my ajax request :

    $("input:checkbox:not(:checked)").each(function() {
        formData.set($(this).attr('name'), formData.has($(this).attr('id')) ? '1' : '0');
    });  
    

    Then, on the Symfony side, I had to override the BooleanToStringTransformer behaviour, that returns true for whatever string and false only for null value. Making a change in the last line, we now return false if the value doesn't match the value defined for true ("1" by default). So if the value returned by the form is "0", we get false, as expected.

    public function reverseTransform($value)
    {
        if (null === $value) {
            return false;
        }
    
        if (!is_string($value)) {
            throw new TransformationFailedException('Expected a string.');
        }
    
        return ($this->trueValue === $value); // initially: "return true;" 
    }
    

    Following the docs, I made my own DataTransformer, as well as a custom AjaxCheckboxType

    Unfortunately, it seems that Symfony uses both DataTransformers (mine and the original one), one after the other, so it didn't work. In the docs they extend TextType not CheckboxType, that must explain the problems I encountered.

    I ended up copying and pasting the whole CheckboxType class in my own AjaxCheckboxType, only changing the DataTransformer's call in order to use mine.

    A much nicer solution would be to totally override the DataTransformer, but I don't know how.

提交回复
热议问题