实际上,我使用带有两个事件侦听器的自定义类型解决了我的问题,用于设置和获取翻译值:
/**
* build fields
* @param \Symfony\Component\Form\FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
/**
* merge new translation
*/
$builder->addEventListener(FormEvents::SUBMIT, function(FormEvent $event) use ($options) {
//test
$form = $event->getForm();//form
$data = $event->getData();//products
$newTranslation = $event->getData();
$key=$options['translation_property'];
$lang=$this->getLocale($options);
$entity=$form->getParent()->getData();
$setter='set'.strtoupper($key);
$getter='get'.strtoupper($key);
$entity->translate($lang)->$setter($newTranslation);
$entity->mergeNewTranslations();
});
/**
* Populate with data
*/
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) use ($options) {
$data = $event->getData();//products
$form = $event->getForm();//form
$key=$options['translation_property'];
$lang=$this->getLocale($options);
$entity=$form->getParent()->getData();
$setter='set'.strtoupper($key);
$getter='get'.strtoupper($key);
$oldValue=$entity->translate($lang,false)->$getter();//no fallback
$event->setData($oldValue);
});
}
字段未映射。可以直接提供翻译属性名称和语言。
/**
* Defauls
* @param \Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'translation_path'=>'translations',
'translation_property' => null,
'translation_lang'=>null,//getLocale or set in form type
'mapped'=>false
));
}
并键入继承表单基本文本。
public function getParent()
{
return 'text';
}
将其定义为 twig 扩展服务 (translation_text) 后,您可以很容易地使用它:
$builder
->add('name')
->add('key')
->add('translate1', 'translation_text',
array(
'translation_property'=>'translate1',
'translation_lang'=>null
))