簡體   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