我正在使用Symfony 3.4
。假设存在具有某些属性的实体Task
,例如title
、note
等。
当创建自定义FormType以允许用户创建新的Task
实体时,每个实体属性通常使用其内部名称添加:
class TaskType extends AbstractMoneyControlBaseType {
public function getBlockPrefix() {
return 'app_task';
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title', TextType::class, [
'label' => 'The Title'
])
->add('note', TextType::class, [
'label' => 'A Note'
]);
...
}
}
这将呈现名称为app_task[title]
和app_task[note]
的表单字段。是否可以使用自定义名称?
当然,Symfony使用标识属性并将输入映射到实体。但是,通过将字段映射到不同的名称来指定不同的名称并不困难,或者通过将字段名称映射到实体属性来指定相反的名称也不困难。
类似这样的东西:
$builder
->add('title', TextType::class, [
'label' => 'The Title',
'renderedName' => 'customTitleName',
])
->add('note', TextType::class, [
'label' => 'A Note'
'renderedName' => 'customNoteName',
]);
OR
$builder
->add('customTitleName', TextType::class, [
'label' => 'The Title',
'mappedFieldName' => 'title',
])
->add('customNoteName', TextType::class, [
'label' => 'A Note'
'mappedFieldName' => 'note',
]);
我找不到这样的解决方案。那么,以某种方式使用自定义字段名是可能的吗
可能的解决方案是使用属性路径
$builder
->add('customTitleName', TextType::class, [
'label' => 'The Title',
'property_path' => 'title',
'renderedName' => 'customTitleName',
])
->add('note', TextType::class, [
'label' => 'A Note'
'renderedName' => 'customNoteName',
]);