Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Editing json_array field with symfony form

In order to edit a json_array symfony field type of an entity, I am trying to convert it to an editable string with a text area in a form.

I have created a DataTransformer which is making the conversion JSONString <-> array:

/**
 * 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 with the form builder I am able to convert the array to string like that:

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

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

How should I do ?

like image 829
user2903807 Avatar asked May 16 '14 19:05

user2903807


1 Answers

It might be that the text you enter into the textarea is not a valid JSON. Try to copy the text into this tool to validate the syntax: http://jsonlint.com/

I would strongly recommend that you integrate some validation into your transformer:

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

       return $modelData;
    }
like image 169
afilina Avatar answered Sep 25 '22 02:09

afilina