Symfony 2表单构建器自定义选项可用于树枝

时间:2014-11-28 12:17:34

标签: php forms symfony twig

我想做这样的事情:

$builder->add('firstname', 'text', array(
                    'myCustomOption' => 'optionValue'
                ));

所以我可以在myForm.html.twig中使用myCustomOption,如下所示:

{% block form_row -%}
    {{ myCustomOption }}
{%- endblock form_row %}

但在这种情况下,我得到:

  

选项" myCustomOption"不存在。已知的选项是:[..]

2 个答案:

答案 0 :(得分:1)

这就是答案:类型扩展

它允许扩展所需的表单类型email/phone/checkbox或组text/entity/choice,甚至可以扩展所有可用的form(请记住,一个元素可以包含少量类型。例如,输入email将是form, text, email的类型

只需创建扩展程序类:

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TextTypeExtension extends AbstractTypeExtension {

    public function getExtendedType() {
        return 'form'; // What type should be extended
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        // Add optional option - you can also add required options
        // and available values of this option
        $resolver->setOptional(array('myOption'));
    }

     public function buildView(FormView $view, FormInterface $form, array $options) {
        // You can put any logic here
        // For example 'myOption' => 'big' can be transformed to 
        // 'myOption' => '300px'
        if (array_key_exists('myOption', $options)) {
            // Add your option to twig template
            $view->vars['myOption'] = $options['myOption'];
        }
    }

}

将课程添加为服务:

services:
    acme_demo_bundle.image_type_extension:
        class: Acme\DemoBundle\Form\Extension\TextTypeExtension
        tags:
            - { name: form.type_extension, alias: form }

现在你可以这样做:

$builder->add('MyInput', 'text', array('myOption' => array('whateverYouNeed')));

<强>来源: http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html

答案 1 :(得分:-1)

尝试这样的事情:

class MyTextType extends AbstractType
{

    public function getParent()
    {
        return 'text';
    }

    public function getName()
    {
        return 'my_text';
    }

    ....

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver
            ->setDefaults([
                'myOption' => null
            ])
        ;
    }    

    ....
}

服务定义:

acme_demo_bundle.text_type:
    class: Acme\DemoBundle\Form\Type\MyTextType
    tags:
        - { name: form.type, alias: my_text }

用法:

$builder->add('someName', 'my_text', ['myOption' => $value])