symfony - 从 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()
方法,它只读取字符串。
是否有可能以另一种方式做到这一点?
解决方案
回调引用实体 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
需要手动重新设置它们。如果您不使用组/选项卡,可能可以跳过它,否则它会抛出异常,说明该字段已经呈现。
推荐阅读
- python - 如何擦除在 PIL/Pillow 上创建的图像?
- python - 已安装软件包时出现 ModuleNotFoundError
- c# - 为什么类库项目中的第 3 方程序集引用需要在其他项目中引用 C# 中的库项目时再次添加?
- android - RecyclerView 多个标题
- ruby-on-rails - 生产环境中引入了一系列新的、神秘的 ActiveRecord 错误
- python - 'Encoder/conv6/Conv2D' 从 2 中减去 3 导致的负维度大小
- angular - 使用从 Angular 组件调用的 Mongoose 的子文档数组更新文档失败
- .htaccess - 每个网站有多个 htaccess 文件?
- android - AOSP:无法将预构建的静态库放入它们的中间文件夹以链接到其他模块
- c# - c#中最通用的函数类型是什么