简体   繁体   中英

FOSRestBundle POST Entity with relations without forms

I want to call my API with a JSON like this :

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

This is my POST function in SurveyController.php

   /**
     * @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;
    }

This is working great i can create a survey with questions, but i'm asking if i am doing wrong indeed i haven't find any exemple like this on internet. All exemple use Symfony Form in order to validate.

Moreover this method can't validate question entity so i'm looking for an exemple on how i can save entity with relations at the same time with validations without using this in my controller :

$form = $this->createForm(SurveyType::class, $survey);
form->submit($request->request->all());
if ($form->isValid()) {

I don't want to create a form for all my entity i just want to use annotations, and the power of deserialization.

Thanks !

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;

Working great with "@Assert\\Valid()"

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

Response

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

So it's working very well , what a shame, that i haven't found an exemple like this on internet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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