首页 > 解决方案 > 从 type_options 访问实体属性

问题描述

在我的实体中,我用回调定义了一个字段颜色。颜色只能在颜色列表中选择(const在此class

/**
 * @ORM\Entity(repositoryClass="App\Repository\EventTagRepository")
 */
class EventTag
{
    const COLORS = [
        "primary"=>"primary", 
        "secondary"=>"secondary", 
        "success"=> "success", 
        "danger"=>"danger", 
        "warning"=>"warning", 
        "info"=>"info", 
        "light"=>"light", 
        "dark"=>"dark"
    ];

   /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Choice(callback="getColors")
     */
    private $color;

    public function getColors()
    {
        return $this::COLORS;
    }

当我在 easy-admin 中创建表单时,我想在choice类型选项中访问此回调,以防止用户选择错误的颜色。

EventTag:
            class: App\Entity\EventTag
            list:
                actions: ['-delete']
            form:
                fields:
                    - { type: 'group', label: 'Content', icon: 'pencil-alt', columns: 8 }
                    - 'name'
                    - { property: 'color', type: 'choice', type_options: { expanded: false, multiple: false, choices: 'colors'} }

不幸的是,在type_options我没有找到访问实体属性的方法,而不是搜索getColors(), IsColors(),hasColors()方法,它只读取字符串。

是否有可能以另一种方式做到这一点?

标签: symfonyeasyadmin

解决方案


回调引用实体 const:

您可以使用

@Assert\Choice(choices=EventTag::COLORS)

在 PHP 实体中和

choices: App\Entity\EventTag::COLORS 

在 YAML 配置中

回调指的是更具体的值:

您需要手动扩展 AdminController

public function createCategoryEntityFormBuilder($entity, $view)
    {
        $formBuilder = parent::createEntityFormBuilder($entity, $view);

        $field = $formBuilder->get('type');
        $options = $field->getOptions();
        $attr = $field->getAttributes();

        $options['choices'] = $formBuilder->getData()->getTypeLabels();
        $formBuilder->add($field->getName(), ChoiceType::class, $options);
        $formBuilder->get($field->getName())
            ->setAttribute('easyadmin_form_tab', $attr['easyadmin_form_tab'])
            ->setAttribute('easyadmin_form_group', $attr['easyadmin_form_group']);

        return $formBuilder;
    }

擦除属性时,我们$formBuilder->add需要手动重新设置它们。如果您不使用组/选项卡,可能可以跳过它,否则它会抛出异常,说明该字段已经呈现。


推荐阅读