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 ?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With