2

I've been trying to display form with data json. I can't understand what I need to do that form have several input fields with TextType? One value json in one input field.

I know how view json array in twig without component form but I want view json with Symfony 4 component form.

This is json array

[{"name":"PHP","image":"php.png"},{"name":"java","image":"java.png"},{"name":"postgresql","image":"postgresql.png"},{"name":"JS","image":"js.png"}]

This is my code:

Class ProjectsController

class ProjectsController extends BaseAdminController {

  public function createEntityFormBuilder($entity, $view)
  {
    $formBuilder = parent::createEntityFormBuilder($entity, $view);

    $formBuilder
        ->add('title')
        ->add('description', TextareaType::class)
        ->add('technology', ProjectTechnologyType::class)
        ->add('type', ProjectType::class)
        ->add('url');

    return $formBuilder;
  }
}

Class ProjectTechnologyType

class ProjectTechnologyType extends AbstractType {

  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
        ->add('image', ProjectJsonType::class);

    $builder->get('image')
        ->addModelTransformer(new CallbackTransformer(
            function ($technologyAsArray) {
                return json_encode($technologyAsArray);
            },
            function ($technologyAsJson) {
                return json_decode($technologyAsJson);
            }
        ));
  }

  public function configureOptions(OptionsResolver $resolver)
  {
    $resolver->setDefaults(array(
        'data_class' => ProjectTechnology::class
    ));
  }
}

Class ProjectJsonType

class ProjectJsonType extends AbstractType{

  public function configureOptions(OptionsResolver $resolver)
  {
    $resolver->setDefaults([]);
  }

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

Twig

{% block main %}
{% block entity_form %}
    {{ form_row(form.title) }}
    {{ form_row(form.description) }}
    {{ form_row(form.type) }}
    {{ form_row(form.technology) }}
    {{ form_row(form.url) }}
{% endblock entity_form %}
{% endblock %}
2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.