Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

symfony - How can I make a custom field type in symfony2?

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 end date) into two different text-box.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

What you need is to make:

  1. New TestBundleFormExtensionCoreTypeDateRangeType which extends SymfonyComponentFormAbstractType

    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: TestBundleFormExtensionCoreTypeDateRangeType
            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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...