Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit json data in a field in Easy Admin Bundle?

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?

like image 850
Anton Smatanik Avatar asked Apr 06 '17 13:04

Anton Smatanik


1 Answers

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.

like image 51
Bonewolf Avatar answered Oct 30 '22 09:10

Bonewolf