Home > Net >  Render a post if is_verified = true in Symfony Controller
Render a post if is_verified = true in Symfony Controller

Time:08-22

I'm building an app with Symfony, and I would like to render a post only if is_verified = true but I don't know where to put this condition in the controller and to access the property (is_verified). Please someone to help me.

Controller.php :

#[Route('/annonce')]
class AnnonceController extends AbstractController
{
#[Route('/', name: 'app_annonce_index', methods: ['GET'])]
public function index(AnnonceRepository $annonceRepository): Response
{
        return $this->render('annonce/index.html.twig', [
            'annonces' => $annonceRepository->findAll(),
        ]);
}

#[Route('/new', name: 'app_annonce_new', methods: ['GET', 'POST'])]
public function new(Request $request, AnnonceRepository $annonceRepository): Response
{
    $annonce = new Annonce();
    $form = $this->createForm(AnnonceType::class, $annonce);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $annonceRepository->add($annonce, true);

        return $this->redirectToRoute('app_annonce_index', [], Response::HTTP_SEE_OTHER);
    }

    return $this->renderForm('annonce/new.html.twig', [
        'annonce' => $annonce,
        'form' => $form,
    ]);
}

#[Route('/{id}', name: 'app_annonce_show', methods: ['GET'])]
public function show(Annonce $annonce): Response
{
    return $this->render('annonce/show.html.twig', [
        'annonce' => $annonce,
    ]);
}

The entity file :

#[ORM\Entity(repositoryClass: AnnonceRepository::class)]
class Annonce
{

#[ORM\Column]
private ?bool $is_verified = false;


public function getIsVerified(): ?bool
{
    return $this->is_verified;
}

public function setIsVerified(bool $is_verified): self
{
    $this->is_verified = $is_verified;

    return $this;
}
}

Thank you for any help

CodePudding user response:

You could do this in your show method:

#[Route('/{id}', name: 'app_annonce_show', methods: ['GET'])]
public function show(Annonce $annonce): Response
{
    if (!$annonce->getIsVerified()) {
        throw $this->createNotFoundException();
    }

    return $this->render('annonce/show.html.twig', [
        'annonce' => $annonce,
    ]);
}

and this in your index method:

#[Route('/', name: 'app_annonce_index', methods: ['GET'])]
public function index(AnnonceRepository $annonceRepository): Response
{
    return $this->render('annonce/index.html.twig', [
        'annonces' => $annonceRepository->findBy(['is_verified' => true]),
    ]);
}
  • Related