Reputation: 321
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 %}
Upvotes: 0
Views: 2960
Reputation: 1055
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 %}
Upvotes: 3