1

I am a beginner in symfony 4, and I wanted to count the recording of an object, but it does not work. this is my code

// Function count() in my repository class

public function count()
{
    return $this->createQueryBuilder('d')
        ->select('count(d.codeMarche) as count')
        ->getQuery()
        ->getSingleScalarResult();
}

// in my controller class, i called my function count()

/**
  * @Route("/", name="home")
  */
public function hom(MarcheDAORepository $repo){
   $count = $repo->count();

    return $this->render('index/home.html.twig', ['nbrDAO'=>$count]);
}

i need your help!!

Matteo
  • 37,680
  • 11
  • 100
  • 115
m.deye
  • 41
  • 2
  • 6
  • define *does not work* please. Any error message? What's the result of `var_dump($count);` ? – Cid Mar 18 '19 at 09:44
  • ErrorException Warning: Declaration of App\Repository\MarcheDAORepository::count() should be compatible with Doctrine\ORM\EntityRepository::count(array $criteria) – m.deye Mar 18 '19 at 09:56
  • the method `count` is already defined in [EntityRepository](the https://www.doctrine-project.org/api/orm/latest/Doctrine/ORM/EntityRepository.html) class so try to rename as example `countMarche` and see what happen – Matteo Mar 18 '19 at 09:58
  • Thanks!! it's worked but i have also an exception string(2) "10", number 10 is th numbre of recording – m.deye Mar 18 '19 at 10:04
  • ok you can use the default count implementation so try to call the count() method of the parent class and should return an integer value – Matteo Mar 18 '19 at 10:54

2 Answers2

2

The count method is already defined in the parent class so you can simply omit your implementation and use the default one (that return an int value as the doc suggest) or rename your method if you want to use a custom implementation, as example

public function countCodeMarche()
{
    return $this->createQueryBuilder('d')
        ->select('count(d.codeMarche) as count')
        ->getQuery()
        ->getSingleScalarResult();
}

That will return a string and you should cast to int if you need a different type.

Matteo
  • 37,680
  • 11
  • 100
  • 115
-3

You can do that by the following code :

public function hom(MarcheDAORepository $repo){
   $items = $repo->findAll();
   $count=count($items);
    return $this->render('index/home.html.twig', ['nbrDAO'=>$count]);
}
c.brahim
  • 170
  • 1
  • 4