是的,我知道之前已经问过并灰心,但是我有一个很好的用例。我有兴趣学习以视角为导向的补充方法。
用例:
我有一个实体,例如Venue (id, name, capacity)
,我将其用作EasyAdmin中的集合。为了渲染选择,我要求该实体具有字符串表示。
我希望显示器说%name% (%capacity% places)
。
正如您正确猜到的那样,我需要" ploce "一词。
我可能想做
- 直接在实体的
__toString()
方法中 - 通过正确渲染
__toString()
输出
在表单视图中
我也不知道如何实施,但我同意第一种方法违反了MVC模式。
请建议。
显示为 %name% (%capacity% places)
只是您的表单视图中的"可能"表示形式,因此我会将此非常具体的表示形式转移到您的表单类型中。
您的 venue 实体的__toString()
方法中可以属于什么:
class Venue
{
private $name;
... setter & getter method
public function __toString()
{
return $this->getName();
}
}
messages.en.yml :
my_translation: %name% (%capacity% places)
接下来您的表单类型使用Choice_label(也值得知道:choce_translation_domain):
use SymfonyComponentTranslationTranslatorInterface;
class YourFormType extends AbstractType
{
private $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'venue',
EntityType::class,
array(
'choice_label' => function (Venue $venue, $key, $index) {
// Translatable choice labels
return $this->translator->trans('my_translation', array(
'%name%' => $venue->getName(),
'%capacity%' => $venue->getCapacity(),
));
}
)
);
}
}
&还将您的表格类型注册为 services.yml 中的服务:
your_form_type:
class: YourBundleNamespaceFormYourFormType
arguments: ["@translator"]
tags:
- { name: form.type }
我针对该问题实现了一个或多或少复杂的解决方案,请参阅我的答案:https://stackoverflow.com/a/54038948/2564552