【问题标题】:Symfony: How to use translation component in entity __toString?Symfony:如何在实体 __toString 中使用翻译组件?
【发布时间】:2017-08-28 19:35:43
【问题描述】:

是的,我知道以前有人问过这个问题并且不鼓励这样做,但我有一个很好的用例。我有兴趣学习面向视图的补充方法。

用例:

我有一个实体,比如Venue (id, name, capacity),我将其用作 EasyAdmin 中的集合。为了呈现选择,我要求该实体具有字符串表示形式。

我希望显示器显示%name% (%capacity% places)

你猜对了,我需要翻译“places”这个词。

我想这样做

  1. 直接在实体的__toString()方法中
  2. 在表单视图中通过正确呈现__toString() 输出

我也不知道如何实现,但我同意第一种方法违反了 MVC 模式。

请指教。

【问题讨论】:

    标签: symfony localization internationalization symfony2-easyadmin


    【解决方案1】:

    将其显示为 %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(也值得知道:choice_translation_domain):

    use Symfony\Component\Translation\TranslatorInterface;
    
    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: Your\Bundle\Namespace\Form\YourFormType
      arguments: ["@translator"]
      tags:
        - { name: form.type }
    

    【讨论】:

    • 这如何进入 EasyAdmin?
    【解决方案2】:

    我为这个问题实现了一个或多或少复杂的解决方案,请参阅我对这个相关问题的回答:https://stackoverflow.com/a/54038948/2564552

    【讨论】:

      猜你喜欢
      • 2015-01-20
      • 2012-12-20
      • 1970-01-01
      • 2019-03-08
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多