Search code examples
phpsymfony

Symfony 5 - Emptying elements from a table by user


I need to create a button to empty elements from my table "scan" but only for the connected user. scan table 1

scanner_id and plante_id are both in ManyToOne, scanner_id is the "user" and plante_id a "plant" from the table plante.

I already added a button to delete unique element 1 by 1 on my page and it works well. Now I would like to clear all elements with one action but only for the right user.

My code to delete 1 element 1 by 1 in my controller:

/**
 * Supprimer une plante dans l'espace personnel utilisateur
 * @Route("/compte/scan/{id}/delete", name="scan_delete")
 * @param Scan $scan
 * @param EntityManager $manager
 * @return Response
 */
public function delete(Scan $scan, EntityManagerInterface $manager) {
    $manager->remove($scan);
    $manager->flush();

    $this->addFlash("success", "la plante {$scan->getPlante()} a bien été supprimée");

    return $this->redirectToRoute('compte_scan');
}

My User Entity :

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @UniqueEntity(fields={"email"}, message="Cette adresse mail est déjà utilisée, veuillez en choisir un autre")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\Column(type="json")
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

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

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

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

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

    /**
     * @ORM\OneToMany(targetEntity=Scan::class, mappedBy="scanner")
     */
    private $scans;

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

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

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

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

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_ELEVE';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    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 getClasse(): ?string
    {
        return $this->classe;
    }

    public function setClasse(string $classe): self
    {
        $this->classe = $classe;

        return $this;
    }

    public function getPseudo(): ?string
    {
        return $this->pseudo;
    }

    public function setPseudo(string $pseudo): self
    {
        $this->pseudo = $pseudo;

        return $this;
    }

    /**
     * @return Collection|Scan[]
     */
    public function getScans(): Collection
    {
        return $this->scans;
    }

    public function addScan(Scan $scan): self
    {
        if (!$this->scans->contains($scan)) {
            $this->scans[] = $scan;
            $scan->setScanner($this);
        }

        return $this;
    }

    public function removeScan(Scan $scan): self
    {
        if ($this->scans->removeElement($scan)) {
            // set the owning side to null (unless already changed)
            if ($scan->getScanner() === $this) {
                $scan->setScanner(null);
            }
        }

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

Solution

  • Should work fine.

    /**
     * @Route("/compte/scan/clear", name="scan_clear")
     * @param EntityManagerInterface $entityManager
     * @return Response
     */
    public function clear(EntityManagerInterface $entityManager) {
      $user = $this->getUser(); 
      $user->getScans()->clear();
      $entityManager->flush();
    
      $this->addFlash("success", "Votre liste de plante à été vidé");
      return $this->redirectToRoute('compte_scan');
    }
    

    If items are not removed from the database when flushing, you might want to loop over the scans and explicitely call $entityManager->remove($scan), then flush.

    $user = $this->getUser();
    foreach($user->getScans() as $scan) {
      $entityManager->remove($scan);
    }
    $entityManager->flush();