【问题标题】:How to get a custom value for a field type in sonata?如何在奏鸣曲中获取字段类型的自定义值?
【发布时间】:2021-09-02 23:41:28
【问题描述】:

在 Sonata 中,当我创建带有choiceType 的合同时,用户可以选择contract1 或contract2,在我的数据库中我会得到contract1 的“451”和contract2 的“678”。
在我的字段列表中显示了我的所有数据,但对于我的合同,我有“451”或“678”,我想要的是合同 1 或合同 2,而不是这些数字。
这是我创建合同的领域:

$mapper
            ->add('contract', ChoiceType::class, [
                'choices' => [
                    'contract1' => '451',
                    'contract2' => '678',
                ],
            ])

在我的字段代码中,我不知道如何判断它是 451 还是 'contract1'。我是这样开始的:

->add('contract', null, [
                'label' => 'Contract',
            ])

有什么想法吗?

【问题讨论】:

    标签: symfony sonata-admin


    【解决方案1】:

    您可以使用表单实体类型来解决您的问题:

    $builder->add('contract', EntityType::class, [
        // looks for choices from this entity
        'class' => Contract::class,
        // uses the Contrzct.name property as the visible option string
        'choice_label' => 'name',
        // Query builder to select your to specific contract
        'query_builder' => function (ContractRepositoty $contractRepository) {
            return $contractRepository->createQueryBuilder('support_time_slot')
                ->where('contract.id  in :ids')
                ->setParameter('ids', [461,678])
                ->orderBy('contract.name');
            },
        // used to render a select box, check boxes or radios
        'multiple' => true,
        'expanded' => true,
    ]);
    

    【讨论】:

      【解决方案2】:

      我找到了解决方案。我创建了一个特定的模板,并在其中翻译了我想要的值:

      ->add('contract', null, [
           'label' => 'Contract',
           'template' => 'AdminBundle:ContractAdmin:list__operation.html.twig'
          ])
      

      还有我的树枝:

      {% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
      
      {% block field %}
          {% if value %}
              {{ ('contract.operation.'~value~'.value')|trans }}
          {% endif %}
      {% endblock %}
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-11
        • 2016-04-17
        • 2015-11-09
        • 2016-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-03
        相关资源
        最近更新 更多