Monday, January 31, 2022

[FIXED] Twig for loop can't find record in MySQL database

Issue

My for loop doesnt seem to be able to find any records in my database.

My loop:

            {% for school in scholen %}
                <li>{{ scholen.naam|e }}</li>
            {% else %}
                <li>no user found</li>
            {% endfor %}

My result.

If I remove the else it's just 'empty' underneath "Scholen"

This is my controller

namespace App\Controller;


use App\Entity\School;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class SchoolController extends AbstractController
{
    /**
     * @Route ("/scholen", name="scholen")
     * Method ({"GET", "POST"})
     */

    public function schoolgegevens()
    {
        $scholen = $this->getDoctrine()
            ->getRepository(School::class);


        return $this->render("security/school.html.twig", ["scholen" => $scholen]);
    }

} 

My database table "Scholen".


Solution

Look at this code :

        $scholen = $this->getDoctrine()
            ->getRepository(School::class);

$scholen contains your repository, not your data. You must do something like

    public function schoolgegevens(SchoolRepository $schoolRepository)
    {
        $scholen = $schoolRepository->findAll();

        return $this->render("security/school.html.twig", ["scholen" => $scholen]);
    }


Answered By - shaax

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.