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:一些自定義約束)。 –