如何在Type类中访问我的Service(DependencyInjection)? [英] How access my Service (DependencyInjection) inside my Type classes?
本文介绍了如何在Type类中访问我的Service(DependencyInjection)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个Service(DependencyInjection),并在我的控制器上将其用作:
I have a Service (DependencyInjection) that i create, and i use that on my controllers as:
$this->get("service_name")->someMethod()
我想知道如何使用
这是我的示例类表格:
namespace Company\SampleBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class AnswerType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options) {
// I want use: $this->get("service") here, how can i use that?
$builder->add('answer', 'textarea');
}
public function getName() {
return 'answer';
}
public function getDefaultOptions(array $options) {
return array(
'data_class' => 'Company\SampleBundle\Entity\Answer',
);
}
}
谢谢
推荐答案
您可以使用 $ options
来实现。这意味着您需要相应地修改 getDefaultOptions
。
You can use the $options
to achieve this. This implies you modify the getDefaultOptions
accordingly.
public function getDefaultOptions(array $options) {
return array(
'service' => null,
'data_class' => 'Company\SampleBundle\Entity\Answer',
);
}
在您的控制器中,当您调用 createForm()时
使用 $ options
参数,例如:
In your controller, when you call createForm()
use the $options
argument, like this:
$this->createForm('Answer', null, array('service' => $service))
这篇关于如何在Type类中访问我的Service(DependencyInjection)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文