我正在尝试使用自定义表单类型实现 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">