我已经定义了一个这样的自定义表单:
class EditOwnerProfileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add("user", new UserType())
->add("dog", new DogType())
->add('save', 'submit');
}
public function getName()
{
return 'edit_owner';
}
}
我想创建这个表单并使用如下数据对其进行初始化:
$user = new User();
$user->setLatitude(1.1)
->setLongitude(2.2)
->setAddress("custom address");
$dog = new Dog();
$dog->setDogName("Bruno")
->setDogSize("small")
->setDogBreed("Bulldog");
$formData = array(
"user" => $user,
"dog" => $dog
);
$form = $this->createForm(new EditOwnerProfileType(), $formData, array("csrf_protection" => false))->handleRequest($request);
DogType
并且UserType
只有NotBlank
约束
每次我想验证数据时,它总是会为每个字段抛出错误,如下所示:
"errors": {
"user": {
"latitude": [
"This value should not be blank."
],
"longitude": [
"This value should not be blank."
],
"address": [
"This value should not be blank."
]
},
"dog": {
"dogName": [
"This value should not be blank."
],
"dogSize": [
"This value should not be blank."
],
"dogBreed": [
"This value should not be blank."
]
},
不应该是我正在初始化所有值吗?那么,如果用户没有为此字段传递任何值,是否使用我定义的值进行初始化?EditOwnerProfileType
在表单上初始化值的正确方法是什么?
编辑:我尝试更改表单创建(仅用于测试),但也没有工作。
$form = $this->createForm(new EditOwnerProfileType(), $formData, array("csrf_protection" => false));
$form->setData($formData);
$form->handleRequest($request);
EDIT2:包括 DogType 和 UserType 代码
class DogType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('dogSize')
->add('dogBreed')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Dog',
));
}
public function getName()
{
return 'dog_type';
}
}
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('latitude')
->add('longitude')
->add('address')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
));
}
public function getName()
{
return 'user_type';
}
}
我正在使用 Symfony 2.7.9