Editing json_array field with symfony form

To edit the json_array symfony field type for an object, I am trying to convert it to an editable string with a text area in the form.

I created a DataTransformer that performs a JSONString ↔ array conversion:

/**
 * Transform an array to a JSON string
 */
public function transform($array)
{
    return json_encode($array);
}

/**
 * Transform a JSON string to an array
 */
public function reverseTransform($string)
{
    return json_decode($string, true);
}

When I create my form using the form constructor, I can convert the array to a line like this:

$builder->add($builder->create('info', 'textarea')->addModelTransformer(new ArrayToJSONStringTransformer()))

But when I submit the form, Symfony creates a new object, and this field is converted as an empty array.

How do i do

+4
source share
1 answer

, , , JSON. , : http://jsonlint.com/

:

    public function reverseTransform($string)
    {
       $modelData = json_decode($string, true);
       if ($modelData == null) {
           throw new TransformationFailedException('String is not a valid JSON.');
       }

       return $string;
    }
+2

Source: https://habr.com/ru/post/1540896/


All Articles