我是Symfony的新手。在这里,我尝试验证JSON参数,但我无法读取数组值。 customer
是我的json对象,没有数组,它正在工作。如果我为批量数据插入添加数组,我就无法读取数组值。
我的代码:
$mydata = $request->get('customer');
$formOptions = [];
$formOptions['isactive'] = true;
foreach($mydata as $val)
{
$form = $this->get('form.factory')->createNamed(
'customer',
CustomerRegistrationFormType::class,
null,
$formOptions
);
$form->handleRequest($request);
if ($form->isValid())
{
return "sucess";
}
else{
return $this->view($form->getErrors(), Response::HTTP_BAD_REQUEST);
}
}
这是我的JSON请求参数:
{
"customer" :
[
{
"firstName": "asdfasdfasdfsdf",
"lastName": "asfd",
"gender": "male",
"email": "sddssddsdkj@sdf.vb",
"phone": "1232547890",
"birthDate": "1991-08-22",
"createdAt": "2017-09-08T11:18:35.605630+00:00",
"Number": "2331313423",
"agreement1": "true",
"agreement2": "true",
"agreement3": "true",
"referral_email": "sdjndsdfreksjd@cgh.fg"
},
{
"firstName": "ldkfasdfsdmnlsmn",
"lastName": "sjdasdffn",
"gender": "male",
"email": "sddssdasdfsdfff23dsdkj@sdf.vb",
"phone": "1232111890",
"birthDate": "1991-08-22",
"createdAt": "2017-09-08T11:18:35.605630+00:00",
"Number": "8824413423",
"agreement1": "true",
"agreement2": "true",
"agreement3": "true",
"referral_email": "sdsdf12jndrsdeksjd@cgh.fg"
}
]
}
如何将数组值发送到get('form.factory')
?
在foreach
内,所有对象都有数组元素。如何将这些数组元素发送到
$form = $this->get('form.factory')->createNamed(
'customer',
CustomerRegistrationFormType::class,
null,
$formOptions
)
我可以使用$ val而不是客户(对象名称),但它不起作用。如果我删除数组并发送单个对象,它就会正常工作。
我的CustomerRegistrationFormType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('firstName', TextType::class, [
'label' => 'First name',
'required' => true,
'constraints' => [
new NotBlank(),
],
]);
$builder->add('lastName', TextType::class, [
'label' => 'Last name',
'required' => true,
'constraints' => [
new NotBlank(),
],
]);
$builder->add('gender', ChoiceType::class, [
'label' => 'Gender',
'required' => false,
'choices' => [
'male' => 'male',
'female' => 'female',
],
]);
$builder->add('email', EmailType::class, [
'label' => 'Email',
'required' => true,
'constraints' => [
new NotBlank(),
new Email(),
],
]);
$builder->add('phone', EmailType::class, [
'label' => 'Phone',
'required' => false,
]);
$builder->add('birthDate', DateType::class, [
'label' => 'Birth date',
'required' => false,
'widget' => 'single_text',
'format' => 'yyyy-MM-dd',
]);
$builder->add('createdAt', DateTimeType::class, [
'label' => 'Creation date',
'required' => false,
'widget' => 'single_text',
'format' => DateTimeType::HTML5_FORMAT,
]);
$builder->add('Number', TextType::class, [
'label' => 'Loyalty card number',
'required' => false,
]);
$builder->add('agreement1', CheckboxType::class, [
'required' => true,
'constraints' => [
new NotBlank(),
],
]);
$builder->add('agreement2', CheckboxType::class, [
'required' => false,
]);
$builder->add('agreement3', CheckboxType::class, [
'required' => false,
]);
$builder->add('referralemail', TextType::class, [
'required' => false,
]);
}