繁体   English   中英

FOSRestBundle POST实体,具有无形式的关系

[英]FOSRestBundle POST Entity with relations without forms

我想用这样的JSON来调用我的API:

{
    "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;

Question.php

  /**
     * @var string
     *
     * @Assert\NotBlank()
     *
     * @ORM\Column(name="label", type="string", length=255)
     */
    private $label;

与“ @Assert \\ Valid()”一起工作非常好

{
    "name" : "my survey",
    "questions" : [
        {
            "label" : "question 1"
        },
        {
            "label" : "question 2"
        },
        {
        }]
}

响应

[
    {
        "property_path": "questions[2].label",
        "message": "This value should not be blank."
    }
]

所以它工作得很好,真可惜,我没有在互联网上找到这样的例子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM