R
R
ragnar_ok2019-07-05 16:20:14
symfony
ragnar_ok, 2019-07-05 16:20:14

Symfony form: how to pass an array?

Three Doctrine entities are given.
Answers to the questions of the questionnaireAnswer :

/**
 * @ORM\Entity(repositoryClass="App\Repository\AnswerRepository")
 */
class Answer
{
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Options", inversedBy="answers")
     * @ORM\JoinColumn(nullable=true)
     */
    private $options;

    public function getOptions(): ?options
    {
        return $this->options;
    }

    public function setOptions(?options $options): self
    {
        $this->options = $options;

        return $this;
    }
    // ...
}

Options for answering the questions of the questionnaireOptions :
class Options
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Answer", mappedBy="options")
     */
    private $answers;

    public function __construct()
    {
        $this->answers = new ArrayCollection();
    }

    /**
     * @return Collection|Answer[]
     */
    public function getAnswers(): Collection
    {
        return $this->answers;
    }

    public function addAnswer(Answer $answer): self
    {
        if (!$this->answers->contains($answer)) {
            $this->answers[] = $answer;
            $answer->setOptions($this);
        }

        return $this;
    }

    public function removeAnswer(Answer $answer): self
    {
        if ($this->answers->contains($answer)) {
            $this->answers->removeElement($answer);
            // set the owning side to null (unless already changed)
            if ($answer->getOptions() === $this) {
                $answer->setOptions(null);
            }
        }

        return $this;
    }
    // ...
}

And the entity with Question questionnaire questions.
I send a POST request with the ID of the answer options to the questions of the questionnaire:
{
    "options": [
        "1",
        "2"
    ],
}

Thus:
$answer = new Answer();
       $form = $this->createFormBuilder($answer)
            ->add('options', EntityType::class, [
                'class' => Options::class,
                'multiple' => true
            ]);

Receive a response:
{
    "code": 500,
    "message": "Expected argument of type \"App\\Entity\\Options or null\", \"Doctrine\\Common\\Collections\\ArrayCollection\" given at property path \"options\"."
}

Help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Antony Tkachenko, 2019-07-05
@ragnar_ok

There is something wrong with your connections.
Options can have several Answer
Answer can have one Options
Either you need ManyToMany, or make a feedback Answer OneToMany -> Options
https://www.doctrine-project.org/projects/doctrine...
And the actual error occurs in
Where explicitly stated what it expects to receive.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question