Customize form field rendering

qdelettre picture qdelettre · Jan 7, 2013 · Viewed 13.4k times · Source

I would like to customize the rendering of a form field in the edit page from sonata admin bundle to include an applet that uses the text content of a field.

I know that I have to edit the configureFormFields function in the admin class, but I need to know 3 things:

  • What is the syntax to provide a field form template
  • Where to put the template file ( which directory )
  • What the template have to looks like.

Answer

qdelettre picture qdelettre · Jan 7, 2013

Found a solution

What i have done is:

  1. Created a field type, lets call it myfieldType in myCompany\myBundle\Form\Type\myfieldType.php

    namespace myCompany\myBundle\Form\Type;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
    
    class myfieldType extends AbstractType
    {
    
        public function getParent()
        {
            return 'text';
        }
    
        public function getName()
        {
            return 'myfield';
        }
    }
    
  2. Registered the Type in app/config/services.yml

    myCompany.myBundle.form.type.myfield:
        class: myCompany\myBundle\Form\Type\myfieldType
        tags:
            - { name: form.type, alias: myfield }
    
  3. In my myentityAdmin class,

     protected function configureFormFields(FormMapper $formMapper)
     {
         $formMapper
         ->add('myfieldname', 'myfield')
         ...
     }
    

    and

    public function getFormTheme() {
        return array('myCompanymyBundle:Admin:myfield_edit.html.twig');
    }
    

    and the template :

    {# src/mycompany/myBundle/Resources/views/Form/myfield_edit.html.twig #}
    {% block myfield_widget %}
        {% spaceless %}
            {{ block('textarea_widget') }}
        {% endspaceless %}
    {% endblock %}
    

And now i can access the form field value by the twig variable "value" !

So easy... when you got it.