7

I have data table which looks like this:

enter image description here

and I wanna edit json data in some user friendly form, not like this:

enter image description here

It's possible to do it quickly, just to change some parameters?

Anton Smatanik
  • 587
  • 1
  • 9
  • 25

1 Answers1

10

If editing of pretty printed JSON is enough for your needs, then create custom form field and data transformer, which formats JSON to pretty print form for template view and back to compact JSON when form is submitted. The solution shown below is based on directory structure and system of Symfony 4.

JSON form field type:

<?php
namespace App\Form\Type;

use App\Form\DataTransformer\JsonToPrettyJsonTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;

class JsonType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);
        $builder->addViewTransformer(new JsonToPrettyJsonTransformer());
    }

    public function getParent()
    {
        return TextareaType::class;
    }
}

Data transformer:

<?php
namespace App\Form\DataTransformer;

use Symfony\Component\Form\DataTransformerInterface;

class JsonToPrettyJsonTransformer implements DataTransformerInterface
{
    public function transform($value)
    {
        return json_encode(json_decode($value), JSON_PRETTY_PRINT);
    }

    public function reverseTransform($value)
    {
        return json_encode(json_decode($value));
    }
}

Easy admin configuration:

easy_admin:
    entities:
        EntityName:
            class: App\Entity\EntityName
            form:
                fields:
                    # other fields
                    - { property: 'propertyName', type: 'App\Form\Type\JsonType' }

More complex editor can be created in same way but probably with overriding of widget template and custom styles plus javascripts.

Bonewolf
  • 149
  • 2
  • 8
  • 2
    Excellent, except, if your type is actually marked as json in the doctrine mapping, you don't have to `json_encode(json_decode(` in either transform method. Just use `json_encode` in the `transform` method and `json_decode` in the `reverseTransform` method. – commonpike Dec 28 '19 at 10:53
  • 1
    For the **reverseTransform** method you want to set the $associative parameter to _TRUE_ in the **json_decode** function, because doctrine mapping expects it to be an array, not an object: `json_decode($value, true)` – BlackWiCKED Nov 30 '20 at 12:39