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 %}
7
  • 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. Commented May 18, 2017 at 14:54
  • Use dump($tasks); in the controller to check what is inside. Commented May 18, 2017 at 14:55
  • @COil where should I get the answer? In my web? Commented May 18, 2017 at 15:04
  • @Matěj Račinský Thank you, I'll try. Commented May 18, 2017 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. Commented May 18, 2017 at 15:06

1 Answer 1

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 %}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.