0

So I've been working with symfony for a while and I'm trying to understand how it works. So, I tried to count how many tasks do I have in my tasks array.

This is my homeController.php class:

 public function succesfulLogin(Request $request)
{

    $repository = $this->getDoctrine()->getRepository('AppBundle:Task');
    $tasks = $repository->findByAuthor($this->getUser()->getUsername());
    $points = 0;

    foreach($tasks as $task){
        $points++;
    }

    return $this->render(
        'userpage.html.twig',array('username' => $username = $this->getUser()->getUsername(), 'tasks' => $tasks, 'points' => $points ));
    $user->getTasks();
   //as I understant I return '$tasks' array to twig with all my tasks
   //so before returning '$tasks' array it should have 21 object in it?(not 13)
   //am I wrong?
}

So I pass 'points' to twig and twig prints out number 13, but when I try to print out all tasks in twig, it says that I have 21 task. There is some twig code:

{% for task in tasks %}//this foreach loop prints out 21 task
        <tr>
            <td id>{{ task.Id }}</td>
            <td>{{ task.Status }}</td>
            <td>{{ task.Name }}</td>
            <td>{{ task.Description }}</td>
            <td>{{ task.Category }}</td>
            <td>{{ task.Author }}</td>
            <td>{{ task.CreationDate|date("m/d/Y") }}</td>
            <td><a id="myLink" href="/edit/{{ task.ID }}" > Edit </a></td>
            <td><a id="myLink" href="/delete/{{ task.ID }}" >Delete</a></td>
            <?php echo 2+2; ?>            </tr>
    {% endfor %}
David
  • 321
  • 1
  • 4
  • 12
  • Check which SQL is generated by `$repository->findByAuthor($this->getUser()->getUsername())` and which SQL is generated by `$user->getTasks()` and try to run these raw SQL queries againt your database. – Matěj Račinský May 18 '17 at 14:54
  • Use `dump($tasks);` in the controller to check what is inside. – COil May 18 '17 at 14:55
  • @COil where should I get the answer? In my web? – David May 18 '17 at 15:04
  • @Matěj Račinský Thank you, I'll try. – David May 18 '17 at 15:04
  • Yes, add a die(); to see in your browser, if there is no die, you will see the result in the debug bar. – COil May 18 '17 at 15:06
  • php inside of a twig template is not going to work well. In any event, twig has support for counting the number of elements in an array. {{ $tasks | length }} Lots of other helper functions as well. https://twig.sensiolabs.org/doc/2.x/filters/length.html – Cerad May 18 '17 at 15:06
  • @Coil wow thanks! Know I know what's wrong :) Problem fixed, thanks everyone! – David May 18 '17 at 15:08

1 Answers1

3

Generally, you should use count() or sizeof() function in PHP for getting count of the objects. So you could just run $points = count($tasks) instead of iterations over $tasks and incrementing.

If you'd like to get array count in twig template, you could use built-in length filter.

{% set tasks_count = tasks|length %}
E.K.
  • 1,045
  • 6
  • 10