O
O
ol sm2017-07-25 09:53:36
symfony
ol sm, 2017-07-25 09:53:36

Symfony3 How to decompose an array, with a global variable?

Good afternoon.
Tell me, please, what am I doing wrong?


class DBGlobalsExtension extends \Twig_Extension
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public function getGlobals()
{
return array (
"ListCategories" => $this->em->getRepository('BloggerBackendBundle:Categories')->findAll()
);
}
public function getName()
{
return "BloggerFrontendBundle:DBGlobalsExtension";
}
}


services:
blogger.twig.db_globals_extension:
class: Blogger\FrontendBundle\Twig\Extension\DBGlobalsExtension
arguments: ['@doctrine.orm.entity_manager']
tags:
- { name: twig.extension }


twig:
globals:
myGlobaService: "@blogger.twig.db_globals_extension"


{% for item in myGlobaService.Globals %}
{{ item.name }}
{% endfor %}

Error:
Key "name" for array with keys "0" does not exist.

{% for item in myGlobaService %}
{% for itemList in item.Globals %}
{{ itemList.name }}
{% endfor %}
{% endfor %}

It also doesn't work.
The essence is here:

class Categories
{
/**
* var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id ;
/**
* var string
*
* @ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* var int
*
* @ORM\Column(name="subCategories_id", type="integer", nullable=true)
*/
private $subCategoriesId;
* Get id
*
* return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
*
* return Categories
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* return string
*/
public function getName()
{
return $this->name;
}
/**
* Set subCategoriesId
*
* @param integer $subCategoriesId
*
* return Categories
*/
public function setSubCategoriesId($subCategoriesId)
{
$this->subCategoriesId = $subCategoriesId;
return $this;
}
/**
* Get subCategoriesId
*
* return int
*/
public function getSubCategoriesId()
{
return $this->subCategoriesId;
}
}

Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor, 2017-07-25
@ol_efk

Few remarks.
1) If the service is registered as global, it does not need to be formatted as a twig-extension and put a tag on it. One of the two is needed.
2) It's not entirely clear why you need to wrap it findAll()in an array. Try to make it simple

return $this->em->getRepository('BloggerBackendBundle:Categories')->findAll()

and in twig your first option should work. Now in the first variant, in the item variable, you get just an array of your categories, the keys of which are numbers, which is what the error says.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question