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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With