Search code examples
symfonytwigsonatasonata-media-bundle

Show the thumbnails instead of the name of img with Symfony2 formbuilder


I am making the form which allow a user to select a img.

Symfony2.8 with sonataMediaBundle/

$form = $this->createFormBuilder($form)
    ->add('media',EntityType::class,array(
            'expanded' => true,
            'class' => "Application\Sonata\MediaBundle\Entity\Media"
            }))
    ->add('save', SubmitType::class, array('label' => 'Create Post'))
    ->getForm();

in twig

{{form_widget(form.media)}}

However it shows the radio buttons with only the name of img.

○AAA.jpg ○BBB.jpg ○CCC.jpg ○DDD.jpg ('○' is radio button)

It is not good design for users.

I want to show the thumbnail of imgs here.

Is there good way to do this?


Solution

  • The easiest way i can imagine is to actually check the radio button with javascript.

    Your Controller :

    //src/AppBundle/Controller/YourController.php
    
    public function yourAction()
    {
        $em = $this->getDoctrine()->getManager();
    
        $medias = $em->getRepository('AppBundle:Media')->findAll();
    
        $entity = new YourEntity();
    
        $form = $this->createForm(YourEntityType::class, $entity);
    
        if ($form->isSubmitted() && $form->isValid()) {
            //... your logic
        }
    
        return $this->render('AppBundle::template.html.twig', array(
            'form' => $form->createView(),
            'medias' => $medias
        ));
    }
    

    Then in your twig file

    {% for media in medias %}
        <img class="to-select" src="{{ media.pathToThumbnail }}" data-id="{{ media.id }}" />
    {% endfor %}
    
    {{ form_start(form) }}
        <!-- assuming you are using bootstrap -->
        <div class="hidden">{{ form_widget(form.media) }}</div>
        {{ form_widget(form.submit) }}
    {{ form_end(form) }}
    
    {% block javascripts %}
        <script>
            //assuming you use jquery
            $('.to-select').click(function () {
                var id = '#form_name_media_' + $(this).data('id');
                var media = $(id);
    
                if (media.is(':checked')) {
                    media.prop('checked', false);
                } else {
                    media.prop('checked', true);
                }
            });
        </script>
    {% endblock javascripts %}