How access my Service (DependencyInjection) inside

2019-03-22 07:34发布

I have a Service (DependencyInjection) that i create, and i use that on my controllers as:

$this->get("service_name")->someMethod()

I want to know how to use that on my Form classes.

Here my example form of class:

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',
        );
    }

}

Thanks

1条回答
看我几分像从前
2楼-- · 2019-03-22 08:31

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',
    );
}

In your controller, when you call createForm() use the $options argument, like this:

$this->createForm('Answer', null, array('service' => $service))
查看更多
登录 后发表回答