Home > Software design >  Problem while Inserting to ManyToOne Table into DB with doctrine and Symfony 4
Problem while Inserting to ManyToOne Table into DB with doctrine and Symfony 4

Time:03-09

I'm using Symfony 4 with doctrine and I try to insert data to ManyToOne Entity relation witch is PromotionAffecte with Entity Promotion (oneToMany) and Utilisateur(oneToMany) however I end up with an error that I can't resolve
Promotion Entity:

/**
 * @ORM\Entity(repositoryClass=PromotionRepository::class)
 */
class Promotion
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=10, nullable=true)
     * @Assert\Choice({"Cadeau", "Remise"})
     */
    private $Type;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\NotBlank(message="Veuillez ajouter description")
     */
    private $description;

    /**
     * @ORM\Column(type="integer")
     * @Assert\NotBlank(message="Veuillez ajouter score")
     */
    private $scoreMin;

    /**
     * @ORM\OneToMany(targetEntity=PromotionAffecte::class, mappedBy="idPromo", orphanRemoval=true)
     */
    private $utilisateur;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $title;

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

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getType(): ?string
    {
        return $this->Type;
    }

    public function setType(?string $Type): self
    {
        $this->Type = $Type;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getScoreMin(): ?int
    {
        return $this->scoreMin;
    }

    public function setScoreMin(int $scoreMin): self
    {
        $this->scoreMin = $scoreMin;

        return $this;
    }

    public function __toString()
    {
        return (string) $this->getId();
    }

    /**
     * @return Collection|PromotionAffecte[]
     */
    public function getUtilisateur(): Collection
    {
        return $this->utilisateur;
    }

    public function addUtilisateur(PromotionAffecte $user): self
    {
        if (!$this->utilisateur->contains($user)) {
            $this->utilisateur[] = $user;
            $user->setIdPromo($this);
        }

        return $this;
    }

    public function removeUtilisateur(PromotionAffecte $user): self
    {
        if ($this->utilisateur->removeElement($user)) {
            // set the owning side to null (unless already changed)
            if ($user->getIdPromo() === $this) {
                $user->setIdPromo(null);
            }
        }

        return $this;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(?string $title): self
    {
        $this->title = $title;

        return $this;
    }
}

Utilisateur Entity:

/**
 * @ORM\Entity(repositoryClass=UtilisateurRepository::class)
 */
class Utilisateur
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $nom;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $prenom;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    private $addresse;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $numTel;

    /**
     * @ORM\Column(type="integer")
     */
    private $score;

    /**
     * @ORM\Column(type="string", length=10)
     */
    private $Type;

    /**
     * @ORM\OneToMany(targetEntity=PromotionAffecte::class, mappedBy="idUser", orphanRemoval=true)
     */
    private $promotion;

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

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNom(): ?string
    {
        return $this->nom;
    }

    public function setNom(string $nom): self
    {
        $this->nom = $nom;

        return $this;
    }

    public function getPrenom(): ?string
    {
        return $this->prenom;
    }

    public function setPrenom(string $prenom): self
    {
        $this->prenom = $prenom;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getAddresse(): ?string
    {
        return $this->addresse;
    }

    public function setAddresse(?string $addresse): self
    {
        $this->addresse = $addresse;

        return $this;
    }

    public function getNumTel(): ?int
    {
        return $this->numTel;
    }

    public function setNumTel(?int $numTel): self
    {
        $this->numTel = $numTel;

        return $this;
    }

    public function getScore(): ?int
    {
        return $this->score;
    }

    public function setScore(int $score): self
    {
        $this->score = $score;

        return $this;
    }

    public function getType(): ?string
    {
        return $this->Type;
    }

    public function setType(string $Type): self
    {
        $this->Type = $Type;

        return $this;
    }

    /**
     * @return Collection|PromotionAffecte[]
     */
    public function getPromotion(): Collection
    {
        return $this->promotion;
    }

    public function addPromotion(PromotionAffecte $promotion): self
    {
        if (!$this->promotion->contains($promotion)) {
            $this->promotion[] = $promotion;
            $promotion->setIdUser($this);
        }

        return $this;
    }

    public function removePromotion(PromotionAffecte $promotion): self
    {
        if ($this->promotion->removeElement($promotion)) {
            // set the owning side to null (unless already changed)
            if ($promotion->getIdUser() === $this) {
                $promotion->setIdUser(null);
            }
        }

        return $this;
    }

    public function __toString()
    {
        return (string) $this->getId();
    }
}

PromotionAffecte Entity:

/**
 * @ORM\Entity(repositoryClass=PromotionAffecteRepository::class)
 */
class PromotionAffecte
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="date")
     */
    private $delai;

    /**
     * @ORM\ManyToOne(targetEntity=Utilisateur::class, inversedBy="promotion")
     * @ORM\JoinColumn(nullable=false)
     */
    private $idUser;

    /**
     * @ORM\ManyToOne(targetEntity=Promotion::class, inversedBy="Utilisateur")
     * @ORM\JoinColumn(nullable=false)
     */
    private $idPromo;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getDelai(): ?\DateTimeInterface
    {
        return $this->delai;
    }

    public function setDelai(\DateTimeInterface $delai): self
    {
        $this->delai = $delai;

        return $this;
    }

    public function getIdUser(): ?Utilisateur
    {
        return $this->idUser;
    }

    public function setIdUser(?Utilisateur $idUser): self
    {
        $this->idUser = $idUser;

        return $this;
    }

    public function getIdPromo(): ?Promotion
    {
        return $this->idPromo;
    }

    public function setIdPromo(?Promotion $idPromo): self
    {
        $this->idPromo = $idPromo;

        return $this;
    }

}

Controller Code :

/**
     * @Route ("/affectePromotion", name="affecterPromotion")
     */
    public function affectPromotion(Request $request)
    {
        $affectation = new PromotionAffecte();
        $form = $this->createForm(PromotionAffecteType::class);
        $form->add("submit", SubmitType::class );
        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()) {
            //$affectation = $form->getData();

            $repo = $this->getDoctrine()->getRepository(Promotion::class)->find($form["idUser"]->getData());
            $repo1 = $this->getDoctrine()->getRepository(Utilisateur::class)->find($form["idPromo"]->getData());

            $affectation->setIdUser($repo);
            $affectation->setIdPromo($repo1);
            $affectation->setDelai($form["delai"]->getData());

            $em = $this->getDoctrine()->getManager();
            $em->persist($affectation);
            $em->flush();

            return $this->redirectToRoute('promotionList');
        }
    return $this->render('promotion_affecte/affectePromotion.html.twig', [

            'form' => $form->createView()
        ]);
    }

And this is PromotionAffecte Form:

class PromotionAffecteType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('delai', DateType::class)
            ->add('idUser', IntegerType::class)
            ->add('idPromo', IntegerType::class)
            ->add('delai', DateType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => PromotionAffecte::class,
        ]);
    }
}

This is the error I end up with:
Expected argument of type "App\Entity\Utilisateur or null", "int" given at property path "idUser".

CodePudding user response:

You don't have the correct PromotionAffecteType. idUser and idPromo are objects, use EntityType for that as shown below:

class PromotionAffecteType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('delai', DateType::class)
            ->add('idUser', EntityType::class,[
                'class' => Utilisateur::class,
                'choice_label' => 'nom',
            ])
            ->add('idPromo', EntityType::class,[
                'class' => Promotion::class,
                'choice_label' => 'title',
            ])
            ->add('delai', DateType::class)
            ->add('submit', SubmitType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => PromotionAffecte::class,
        ]);
    }
}

And change your method in controller to this:

   /**
     * @Route ("/affectePromotion", name="affecterPromotion")
     */
    public function affectPromotion(Request $request)
    {
        $form = $this->createForm(PromotionAffecteType::class);
    
        $form->handleRequest($request);
    
        if($form->isSubmitted() && $form->isValid()) {
            $affectation = $form->getData();
            $em = $this->getDoctrine()->getManager();
            $em->persist($affectation);
            $em->flush();
    
            return $this->redirectToRoute('promotionList');
        }
        return $this->render('promotion_affecte/affectePromotion.html.twig', [
            'form' => $form->createView()
        ]);
    }
  • Related