2

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

    ));

}
1
  • What do you want to do? Could you please explain further? Could you show us line 17 of chartTipos.html.twig? Commented Jan 12, 2015 at 8:21

2 Answers 2

2

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

Comments

0

update your template to be:

{% block artic %}

{{ entities|length }}

{% endblock %}

3 Comments

Sorry, I'll edit the post, i want show the elements of a specific type. Example: 100 animals elements in array is == {{ entities|length }} but I need show the 50 dogs
Your array is numeric, which means you'd need to do, {{ entities[0]|length }} could you perhaps post a sample of what your array is by doing a var_export($entities) on the php side.
in the end I resolved using match and length in javascript. Thanks for help !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.