How can I make a custom field type in symfony2?

后端 未结 3 1473
悲&欢浪女
悲&欢浪女 2020-12-08 15:48

I want to make a custom form field in symfony2 named daterange, which will extends the default symfony date type form field and take date range(start date and e

相关标签:
3条回答
  • 2020-12-08 16:24

    There is a good entry in official cookbook on creating custom field type

    0 讨论(0)
  • 2020-12-08 16:40

    In order to do that, you need to add the following lines into app/config/config.yml

    twig:
        form:
            resources:
                - 'YourSuperBundle:Form:fields.html.twig'
    

    then in src/Your/SuperBundle/Resources/views/Form/fields.html.twig:

    {% extends 'form_div_layout.html.twig' %}
    
    {% block daterange_widget %}
         ... do the customization.
    {% endblock %}
    

    For additional reference please read form customization of Symfony 2.0 book.

    0 讨论(0)
  • 2020-12-08 16:42

    Cause I don't like twig template engine this example only for PHP templating

    What you need is to make:

    1. New TestBundle\Form\Extension\Core\Type\DateRangeType which extends Symfony\Component\Form\AbstractType

      Here you should:
      a. write your own getParent, getName, buildForm methods
      b. getParent return 'field'
      c. getName return 'daterange'
      d. buildForm has $builder->add('start', ...)->add('end', ...)->setAttribute('widget', 'daterange')

    2. Add it to the DI (config.yml as example)

        services:
            form.type.daterange:
                class: TestBundle\Form\Extension\Core\Type\DateRangeType
                tags:
                    -  { name: form.type, alias: daterange }
    
    1. Create new widget for it in TestBundle/Resources/views/Form/daterange_widget.html.php you can take date widget as example. Src/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/date_widget.html.php

    2. Add to config (config.yml as example)

       framework:
           templating:
               form:
                   resources:
                       - 'TestBundle:Form'
    

    And for more widget customization as nefo_x said check form customization.

    0 讨论(0)
提交回复
热议问题