переменная не существует в twig l oop с использованием symfony 4 - PullRequest
0 голосов
/ 25 мая 2020

Я получаю сообщение "Переменная" Миссии "не существует". в ветке l oop,

Я пробовал использовать «если определено» l oop, но мои миссии не отображаются на моем экране.

Я проверял везде, я не знаю, откуда он может взяться.

так что это мой шаблон:

{% extends 'base.html.twig' %}

{% block title 'Agence lorem ipsum' %}

{% block body %}
    <div class="jumbotron text-center">
        <h1>Trouvez une mission qui vous correspond</h1>
        <p>My super est encore en developpement , vous pouvez apporter vos idées via le formulaire de contact</p>
    </div>

    <div class="container">
        <h2>Les dernieres missions</h2>
        <div class="row flex">

            {% for Mission in Missions %}
                <div class="col-3">
                    <div class="card">
                        <div class="card-body">
                            <h5 class="card-title">
                                <a href="{{ path('lesmissions/show.html.twig', {id: mission.id, slug: mission.slug}) }}">{{ mission.titre }}</a>
                            </h5>
                            <p class="card-text">{{ mission.adresse }} ({{ mission.createdat|date('Y-m-d') }})</p>
                            <div class="text-primary" style="font-weight: bold;font-size: 2rem;">{{ mission.gain }} €</div>
                        </div>
                    </div>
                </div>
            {% endfor %}

        </div>
    </div>
{% endblock %}

это моя миссия

<?php

namespace App\Entity;

use App\Repository\MissionRepository;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=MissionRepository::class)
 */
class Mission
{






    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\Column(type="text")
     */
    private $description;

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

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

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

    /**
     * @ORM\Column(type="boolean" , options={"default" : false})
     */
    private $Urgence;

    /**
     * @ORM\Column(type="boolean", nullable=true , options={"default" : false})
     */
    private $Accepted;

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

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

    public function __construct()
    {
        $this->created_at = new \Date();
    }

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

    public function getTitre(): ?string
    {
        return $this->titre;
    }

    public function setTitre(string $titre): self
    {
        $this->titre = $titre;

        return $this;
    }

    public function getSlug(): string
    {
        return (new Slugify())->slugify($this->titre);
    }


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

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

        return $this;
    }

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

    public function setDateDebut(\DateTimeInterface $date_debut): self
    {
        $this->date_debut = $date_debut;

        return $this;
    }

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

    public function setDateFin(?\DateTimeInterface $date_fin): self
    {
        $this->date_fin = $date_fin;

        return $this;
    }

    public function getGain(): ?int
    {
        return $this->gain;
    }

    public function setGain(int $gain): self
    {
        $this->gain = $gain;

        return $this;
    }

    public function getUrgence(): ?bool
    {
        return $this->Urgence;
    }

    public function setUrgence(bool $Urgence): self
    {
        $this->Urgence = $Urgence;

        return $this;
    }

    public function getAccepted(): ?bool
    {
        return $this->Accepted;
    }

    public function setAccepted(?bool $Accepted): self
    {
        $this->Accepted = $Accepted;

        return $this;
    }

    public function getAdresse(): ?string
    {
        return $this->adresse;
    }

    public function setAdresse(?string $adresse): self
    {
        $this->adresse = $adresse;

        return $this;
    }

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

    public function setCreatedAt(?\DateTimeInterface $created_at): self
    {
        $this->created_at = $created_at;

        return $this;
    }
}

вот мой репозиторий

<?php

namespace App\Repository;

use App\Entity\Mission;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\QueryBuilder;


/**
 * @method Mission|null find($id, $lockMode = null, $lockVersion = null)
 * @method Mission|null findOneBy(array $criteria, array $orderBy = null)
 * @method Mission[]    findAll()
 * @method Mission[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class MissionRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Mission::class);
    }

    /**
     * @return Mission[]
     */
    public function findAllVisible(): array
    {
        return $this->findVisibleQuery()
            ->getQuery()
            ->getResult();
    }

    /**
     * @return Mission[]
     */
    public function findLatest(): array
    {
        return $this->findVisibleQuery()
            ->setMaxResults(30)
            ->getQuery()
            ->getResult();
    }

    private function findVisibleQuery(): QueryBuilder
    {
        return $this->createQueryBuilder('m')
            ->where('m.Accepted = false');
    }

    // /**
    //  * @return Mission[] Returns an array of Mission objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('m')
            ->andWhere('m.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('m.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Mission
    {
        return $this->createQueryBuilder('m')
            ->andWhere('m.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}

и, наконец, мой контроллер для моих миссий

<?php

namespace App\Controller;


use App\Entity\Mission;
use App\Repository\MissionRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;



class MissionController extends AbstractController {



    /**
     * @var MissionRepository
     */
    private $repository;
    /**
     * @var EntityManagerInterface
     */
    private $em;

    public function __construct(MissionRepository $repository, EntityManagerInterface $em)
    {
        $this->repository = $repository;
        $this->em = $em;
    }

    /**
     * @return Response
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @Route ("/missions" , name="Missions")
     */
    public function index():Response
    {
        return $this->render('lesmissions/index.html.twig');
    }


    /**
     * @Route("/missions/{slug}-{id}", name="mission.show", requirements={"slug": "[a-z0-9\-]*"})
     * @param Mission $mission
     * @return Response
     */
    public function show(Mission $mission, string $slug): Response
    {
        if ($mission->getSlug() !== $slug) {
            return $this->redirectToRoute('mission.show', [
                'id' => $mission->getId(),
                'slug' => $mission->getSlug()
            ], 301);
        }
        return $this->render('lesmissions/show.html.twig', [
            'mission' => $mission,
            'current_menu' => 'missions'
        ]);
    }


}


?>

(и это контроллер для моей страницы)

<?php

namespace App\Controller;

use App\Repository\MissionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class LesmissionsController extends AbstractController
{
    /**
     * @Route("/lesmissions", name="lesmissions")
     * @param MissionRepository $repository
     * @return Response
     */
    public function index(MissionRepository $repository): Response
    {
        $missions = $repository->findLatest();
        return $this->render('lesmissions/index.html.twig', [
            'missions' => $missions
        ]);
    }

}

заранее спасибо :)

1 Ответ

0 голосов
/ 25 мая 2020

В вашем шаблоне представления:

замените следующую строку:

{% for Mission in Missions %}

на:

{% for mission in missions %}

Пояснение:

Вы проходите missions с вашего контроллера, а не Missions.

...