自定义字段类型的默认属性不会显示在HTML中

时间:2013-04-13 05:42:30

标签: php symfony symfony-2.1 symfony-forms

我正在尝试使用自定义表单类型实现Facebook样式自动填充字段。 JavaScript小部件依赖于类名,所以我将它添加到自定义表单类型类中的attr键,就像我在其他地方所做的那样,但由于某种原因它永远不会显示在输出HTML中: - (

相关代码:

class AutocompleteType extends AbstractType
{
    protected $em;

    public function __construct(ObjectManager $em)
    {
        $this->em = $em;
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'attr' => array(
                'class' => 'autocomplete',
                'data-autocomplete' => '{"url":"'.$options['url'].'"}'
            )

        );
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {

        $resolver->setDefaults(array(
            'url' => false,
            'object' => false,
            'repository' => false,
            'field' => false
        ));

    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new AutocompleteTransformer($this->em, $options['object'], $options['repository'], $options['field']);
        $builder->addModelTransformer($transformer);
    }

    /**
    * {@inheritdoc}
    */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars = array_replace($view->vars, array(
            'url' => $options['url'],
            'object' => $options['object'],
            'repository' => $options['repository'],
            'field' => $options['field']
        ));
    }

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

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

生成的HTML:

<input type="text" required="required" name="post[Tags]" id="post_Tags">

预期的HTML

<input type="text" class="autocomplete" data-autocomplete="url/passed/from/builder" required="required" name="post[Tags]" id="post_Tags">

1 个答案:

答案 0 :(得分:0)

有三种方法,我不知道哪种方法更好

1)在buildForm()方法下,您可以获取并设置属性'attr':

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $attrs = $builder->getAttribute('attr');
    ...
    $builder->setAttribute('attr', $attrs);
}

2)另一种方法是在构建视图下设置属性,我认为它有点逻辑

public function buildView(FormView $view, FormInterface $form, array $options)
{
    $view->vars['attr'] = array_merge(array(
        ....
    ), $view->vars['attr']);
}

3)最新的方法是直接将它们作为变量传递给视图而不是“attr”,然后将它们显示在适当的树枝块中。

我认为第三种是最好的方式,但我不确定。