Php FOSRestBundle POST实体,具有不带表单的关系
我想用JSON调用我的API,如下所示:Php FOSRestBundle POST实体,具有不带表单的关系,php,symfony,Php,Symfony,我想用JSON调用我的API,如下所示: { "name" : "my survey", "questions" : [ { "label" : "question 1" }, { "label" : "question 2" }, { "label" : "question 3" }] } 这是我在SurveyController.php中的POST函数 /** *
{
"name" : "my survey",
"questions" : [
{
"label" : "question 1"
},
{
"label" : "question 2"
},
{
"label" : "question 3"
}]
}
这是我在SurveyController.php中的POST函数
/**
* @Rest\View(statusCode=Response::HTTP_CREATED)
* @ParamConverter("survey", converter="fos_rest.request_body")
* @Rest\Post("/surveys")
*/
public function postSurveysAction(Survey $survey,ConstraintViolationList $violations)
{
if (count($violations))
{
return $this->view($violations, Response::HTTP_BAD_REQUEST);
}
$em = $this->getDoctrine()->getManager();
foreach ($survey->getQuestions() as $question)
{
/* @var $question Question */
$question->setSurvey($survey);
$em->persist($question);
}
$em->persist($survey);
$em->flush();
return $survey;
}
这是伟大的工作,我可以创建一个调查与问题,但我问如果我做错了确实我没有找到任何这样的例子在互联网上。所有示例都使用Symfony表格进行验证
此外,此方法无法验证问题实体,因此我正在寻找一个示例,说明如何在不在控制器中使用此方法的情况下,通过验证同时保存具有关系的实体:
$form = $this->createForm(SurveyType::class, $survey);
form->submit($request->request->all());
if ($form->isValid()) {
我不想为我所有的实体创建一个表单,我只想使用注释和反序列化的功能
谢谢 Survey.php
/**
* @var ArrayCollection
* @JMS\Type("ArrayCollection<AppBundle\Entity\Question>")
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Question", mappedBy="survey", cascade={"persist", "remove"})
* @Assert\Valid()
*/
private $questions;
使用“@Assert\Valid()”效果很好
回应
[
{
"property_path": "questions[2].label",
"message": "This value should not be blank."
}
]
所以它工作得很好,真遗憾,我还没有在互联网上找到这样的例子
{
"name" : "my survey",
"questions" : [
{
"label" : "question 1"
},
{
"label" : "question 2"
},
{
}]
}
[
{
"property_path": "questions[2].label",
"message": "This value should not be blank."
}
]