Unable to extract translation id for form label wi

2019-09-13 21:15发布

问题:

I'm using the JMS Translation Bundle to extract my translations. Everything works, but when I try to extract my translation messages form a form builder I recieve following message:

[JMS\TranslationBundle\Exception\RuntimeException]
  Unable to extract translation id for form label from non-string values, but got "PHPParser_Node_Expr_MethodCall" in /srv/local.project.com/app/../src/Project/MyBundleBundle/Form/Type/EmailType
  .php on line 30. Please refactor your code to pass a string, or add "/** @Ignore */".

The code I use for it is as followed:

public function __construct($translator)
    {
        //translation service passed from controller
        $this->trans = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('email', 'repeated', array(
                'type' => 'email',
                'first_name' => 'email',
                'second_name' => 'email-repeat',
                 //TRANSLATION GIVES ERROR ON NEXT LINE          
                'invalid_message' => $this->trans->trans('online.form.email.errors.equal', array(), 'messages_roadrunner'), 
                'error_bubbling' => true,
                'first_options'  => array('label' => $this->trans->trans("online.form.email.fields.one", array(), 'messages_roadrunner')),
                'second_options' => array('label' => $this->trans->trans("online.form.email.fields.second", array(), 'messages_roadrunner')),
            )
        );

        $builder->add('optin', 'checkbox', array(
            'required'  => false,
            'label' => $this->trans->trans('online.form.email.fields.optin', array(), 'messages_roadrunner')
        ));

    }

The strange thing is that in my controller I use the same thing, but there everything works as normal:

$content['text'] = $this->get('translator')->trans('online.tariff.text.no_advice', array(), 'messages_roadrunner');

Does anyone have any experience with this problem?

Thanks in advance!

回答1:

Don't forget that by default the extractor is configured to automatically extract values from FormBuilder::add() call arguments (see the doc). In your case it expects 'label' to be a string, but it contains a method call, and there goes your error.

This actually means that you don't have to pass the translator into the FormType too.