【问题标题】:access entity property from type_options从 type_options 访问实体属性
【发布时间】:2020-02-25 12:32:05
【问题描述】:

在我的实体中,我用回调定义了一个字段颜色。颜色只能在颜色列表中选择(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() 方法,它只读取字符串。

可以换一种方式吗?

【问题讨论】:

    标签: symfony easyadmin


    【解决方案1】:

    回调引用实体常量:

    你可以使用

    @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 删除了属性,我们需要手动重新设置它们。如果您不使用 Groups/Tabs,可能可以跳过它,否则它会抛出异常,说明该字段已呈现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多