1
我正在使用FosrestBundle和Symfony3构建API。在我的一些工作中,我必须构建表单,并且我希望表单中的某些字段设置为“不需要”。但是当我尝试创建它们时出现错误。当使用FosrestBundle构建表单时,在Symfony3中使用“不需要”
下面是我如何为我的一个实体创建表单:“问题”。
首先我创建了一个QuestionType类,我设定的必要为false:
class QuestionType extends AbstractType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('libelle');
$builder->add('description');
$builder->add('imageRoot');
$builder->add('page', 'integer', array('required' => false));
$builder->add('ligne', 'integer', array('required' => false));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Question',
'csrf_protection' => false
]);
}
}
其次,我在validation.yml文件中配置验证参数:
AppBundle\Entity\Question:
properties:
libelle:
- NotBlank: ~
- Type: string
description:
- NotBlank: ~
- Type: string
imageRoot:
- Type: string
page:
- Type: integer
- GreaterThan:
value: 0
- LessThanOrEqual:
value: 1000
ligne:
- Type: integer
- GreaterThan:
value: 0
- LessThanOrEqual:
value: 1000
第三,我创造了我在控制器中的形式
class ContenuController extends Controller{
/**
* @Rest\View(serializerGroups={"contenu"}, statusCode=Response::HTTP_CREATED)
* @Rest\Post("/lectureContenu/{id}/Questions")
*/
public function postQuestionAction(Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$contenu = $em->getRepository('AppBundle:Contenu')->find($request->get('id'));
$typeQuestion = $em->getRepository('AppBundle:TypeQuestion')->find(1);
if (empty($contenu)) {
return new JsonResponse(['message' => 'Contenu de la question inexistant'], Response::HTTP_NOT_FOUND);
}
$question = new Question();
$question->setContenu($contenu)
->setTypeQuestion($typeQuestion);
$form = $this->createForm(QuestionType::class, $question);
$form->submit($request->request->all()); // Validation des données
if ($form->isValid()) {
$em->persist($question);
$em->flush();
return $question;
} else {
return $form;
}
}
}
最后,当我用示例运行我的代码时以下文件(使用邮差):
{
"libelle": "test",
"description": "test",
"imageRoot": "test"
}
我得到这个错误:
...
"message": "Could not load type \"integer\"",
"class": "Symfony\\Component\\Form\\Exception\\InvalidArgumentException",
...
我不知道为什么!对我而言,一切看起来都正确。请帮忙 !
为什么在'QuestionType'形式的'buildForm'方法中添加'return $ options;'??? –
这是一个错误,我只是删除它:) – kabrice
请添加AppBundle \ Entity \ Question'实体的验证约束和相关代码。 (es:一些自定义约束)。 –