我明白,如果我放
->add('visitor.name', TextType::class, [
'property_path' => 'vistorName'
])
这与<input name="vistorName"
相同
如何为子窗体执行类似操作,将所有子字段作为父字段名称,而不将其作为子数组放入。
$builder->add('customer', CustomerType::class);
客户类型
$builder
->add('name', TextType::class)
->add('email', EmailType::class)
->add('phone', PhoneNumberType::class, [
'default_region' => 'GB', // TODO GLOBAL release
'format' => PhoneNumberFormat::NATIONAL
]);
上面的表格应该生成<input name="name"... <input name="email"...
而不是跟随<input name="customer[name]"...
我怎样才能做到这一点?
以下是完整的代码示例
// Cart model
class Cart {
protected $productName;
/** @var Customer */
protected $customer;
}
// Customer model
Class Customer {
protected $name;
protected $email;
protected $phone;
}
//CustomerType form
$builder
->add('name', TextType::class)
->add('email', EmailType::class)
->add('phone', PhoneNumberType::class, [
'default_region' => 'GB', // TODO GLOBAL release
'format' => PhoneNumberFormat::NATIONAL
]);
// main parent form
class MainFormType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('productName', TextType::class)
->add('customer', CustomerType::class); // need property_path for this, so all the inner fields can be used as parent
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Cart::class,
'required' => false
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'cart';
}
}
它的工作原理相反:
场景:
VisitorEntity:
现在您要更新VisitorEntity customer.name:
class MainFormType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('productName', TextType::class)
->add('customerName', TextType::class, ['property_path'=>'customer.name'])
->add('customerEmail', TextType::class, ['property_path'=>'customer.email'])
->add('customerPhone', TextType::class, ['property_path'=>'customer.phone'])
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Cart::class,
'required' => false
]);
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'cart';
}
}
https://symfony.com/doc/3.4/reference/forms/types/form.html#property-path
type:any default:字段的名称
默认情况下,Fields显示表单域对象的属性值。提交表单时,将提交的值写回对象。
如果要覆盖字段读取和写入的属性,可以设置property_path选项。其默认值是字段的名称。
如果希望在读取或写入对象时忽略该字段,可以将property_path选项设置为false,但不建议使用property_path,则应使用映射选项。