Forms 尽可能的服务于唱诗班?
我有以下代码:Forms 尽可能的服务于唱诗班?,forms,symfony,Forms,Symfony,我有以下代码: namespace Acme\Demo\Form; use Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList; use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList; class MyChoiceList extends LazyChoiceList { protected function loadCho
namespace Acme\Demo\Form;
use Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList;
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
class MyChoiceList extends LazyChoiceList
{
protected function loadChoiceList()
{
return SimpleChoiceList(array('t'=>'test'));
}
}
services.yml:
SMyChoiceList:
class: Acme\Demo\Form\MyChoiceList;
然后,当我尝试这样做时:
$builder
->add('mychoice', 'choice', array('choice_list' => 'SMyChoiceList'
));
我得到:
值为“SMyChoiceList”的选项“choice\u list”的类型应为“null”,“Symfony\Component\Form\Extension\Core\ChoiceList\choicelisterface”
LazyChoiceList
已经实现了ChoiceListInterface
。。。所以我猜Symfony2choice\u list
参数不支持服务,或者我遗漏了什么
我认为它的工作原理与
但我想不会。与
'choice_list' => 'SMyChoiceList'
。。你只是在使用一个字符串
你可以用..直接调用它
'choice_list' => new MyChoiceList()
或者,如果它有依赖项,您可以将其注入表单构造函数中,如
your.form:
class: %your.form.class%
arguments:
- @SMyChoiceList
tags:
- { name: form.type, alias: your_form_alias }
。。然后在你的表格中使用它,比如
protected $choiceList;
public function __construct(ChoiceListInterface $choiceList)
{
$this->choiceList = $choiceList;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('mychoice', 'choice', array(
'choice_list' => $this->choiceList,
))
;
}
更新
要在自定义表单类型中使用选择列表,请执行以下操作(使用与上述设置相同的服务)
你可以用它来代替选择,比如
$builder
->add('something', 'your_form_alias', array(
// Your choice options (expanded, label, attr, etc)
))
;
这都在您之前添加的页面中,更具体地说是的,我知道这是一个字符串。然而,我认为它的工作原理与:。也许我应该建议它作为一种增强。。。顺便说一句,谢谢。如果你想创建一个选择字段,并将其作为选择列表,你需要将选择列表插入到你的表单中,并以与你发布的链接中相同的方式使用它。然后你可以把它称为字段类型而不是选项。等等,等等。你能告诉我你的意思吗?我不确定我是否完全明白。我对我的答案加了一个更好的解释。啊,我现在明白你的意思了。那么另一个表单类型来“包装”选择,嗯?嗯。似乎有点变通,但我想这是把它变成“服务”的唯一方法。再次感谢!:)
$builder
->add('something', 'your_form_alias', array(
// Your choice options (expanded, label, attr, etc)
))
;