Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting Translator service to FormType

Tags:

symfony

I'm trying to find a the most reusable working option for being able to translate from a FormType.

My first option is to declare a service specifically for each FormType this way:

services.yml

form.enquiry:
    class: Acme\DemoBundle\Form\EnquiryType
    arguments: [@translator]

EnquiryType.php

use Symfony\Component\Translation\Translator;
class EnquiryType extends AbstractType {

    public $translator;
    public function __construct(Translator $translator=null)
    {
        $this->translator = $translator;
    }

public function buildForm(FormBuilderInterface $builder, array $options) {
    $tr= $this->translator;
    $msg=$tr->trans('default_error');
    $builder->add ...

MyController.php

 $form = $this->container->get('form.enquiry')->create();
 return $this->render('AcmeDemoBundle:Home:index.html.twig', array(
     'form' => $form->createView()
 ));

gives this error

FatalErrorException: Error: Call to undefined method Acme\DemoBundle\Form\EnquiryType::create()

I'd like to know how to solve it by changing the code or even better finding a better option that allows me to inject the translator service to any FormType without needing to declare each FormType service individually.

like image 385
Arco Voltaico Avatar asked Jul 15 '14 08:07

Arco Voltaico


2 Answers

Your EnqurityType must return whole form so inside buildForm You should create whole form

$builder
->setAction('action')
->setMethod('POST')
->add('field', 'field_type')

And in constructor You should type hint for TranslatorInterface its called design by contract

like image 51
kskaradzinski Avatar answered Oct 04 '22 09:10

kskaradzinski


To make it work properly with Dependency Injection you need to tag it as a form.type:

tags:
    - { name: form.type }

also do not get it from container like a usual service, but use controller helper as it was a normal formType:

$this->createForm(...)

Take a look into: http://symfony.com/doc/2.8/form/form_dependencies.html

like image 29
Rafał Mnich Avatar answered Oct 04 '22 09:10

Rafał Mnich