2013-08-08 25 views

Trả lời

4

Chỉ cần đưa dịch vụ bạn muốn thông qua hàm tạo vào loại biểu mẫu.

class FooType extends AbstractType 
{ 
    protected $barService; 

    public function __construct(BarService $barService) 
    { 
     $this->barService = $barService; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $this->barService->doSomething(); 
     // (...) 
    } 
} 
+2

Bạn cũng sẽ cần phải thêm đối số mới vào khai báo FormType trong tệp dịch vụ, ví dụ: trong services.yml – dxvargas

+0

để làm cho câu trả lời này hoạt động đầy đủ, loại biểu mẫu của bạn phải được [định nghĩa là một dịch vụ] (http://symfony.com/doc/current/form/create_custom_field_type.html#creating-your-field- loại-as-a-dịch vụ) – ShinDarth

3

Nhìn vào this page in the sympfony docs để biết mô tả cách khai báo loại biểu mẫu của bạn dưới dạng dịch vụ. Trang đó có rất nhiều tài liệu và ví dụ tốt.

Cyprian đang đi đúng hướng, nhưng trang được liên kết sẽ tiến thêm một bước nữa bằng cách tạo loại biểu mẫu của bạn dưới dạng dịch vụ và giúp vùng chứa DI tự động dịch vụ.

5

Như một câu trả lời hoàn chỉnh dựa trên câu trả lời trước/bình luận:

Để truy cập vào một dịch vụ từ Loại Mẫu của bạn, bạn phải:

1) Define your Form Type as a service và tiêm các dịch vụ cần thiết vào nó:

# src/AppBundle/Resources/config/services.yml 
services: 
    app.my.form.type: 
     class: AppBundle\Form\MyFormType # this is your form type class 
     arguments: 
      - '@my.service' # this is the ID of the service you want to inject 
     tags: 
      - { name: form.type } 

2) Bây giờ trong lớp học kiểu mẫu của bạn, tiêm nó vào constructor:

// src/AppBundle/Form/MyFormType.php 
class MyFormType extends AbstractType 
{ 
    protected $myService; 

    public function __construct(MyServiceClass $myService) 
    { 
     $this->myService = $myService; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $this->myService->someMethod(); 
     // ... 
    } 
}