Reputation: 23
I want show the numbers of the elements in a array, but I have this problem
Key "idTipoFarmaco" for array with keys "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12" does not exist in FarmacoBundle:Default:chartTipos.html.twig at line 17
Template
{% block artic %}
{{ entities.idTipoFarmaco.nombreFarmaco|length}}
{% endblock %}
Function
public function chartTiposFAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('::Entity')->findAll();
return $this->render('::chartTipos.html.twig', array(
'entities' => $entities
));
}
Upvotes: 2
Views: 4414
Reputation: 3573
Based on your comment on Jonathan (In which you explain that you want to count elements in the entities array which meet certain requirements) I would say you have to apply a filter before getting the length of the array.
See the Symfony documentation about how to create a custom filter.
First create a Twig extention class:
namespace Foo\BarBundle\Twig;
use Doctrine\Common\Collections\Collection;
class YourTwigFiltersExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('filterType', array($this, 'filterType')),
);
}
public function filterType(Collection $entities, $type)
{
return $entities->filter(function ($e) use ($type) {
return $e->getType() == $type; // Replace this by your own check.
});
}
public function getName()
{
return 'your_twig_filters';
}
}
Then register your extension as a service in services.yml (or your xml):
foobar.twig.filters_extension:
class: Foo\BarBundle\Twig\YourTwigFiltersExtension
public: false
tags:
- { name: twig.extension }
And use it as follows in your templates:
{% block artic %}
{{ entities|filterType('dog')|length }}
{% endblock %}
Upvotes: 2
Reputation: 2877
update your template to be:
{% block artic %}
{{ entities|length }}
{% endblock %}
Upvotes: 0