0

In my Symfony project I try to append new array key-value pair into the result I am rendering to twig template file. It has some odd behaviour.

$posts = $this->entityManager->getRepository(Post::class)->getPage($listType, $page, $pageSize);

foreach ($posts['data'] as $post) {
    $post['destinationName'] = $this->destinationService->getDestinationName($posts['data']);
}

return $this->render('posts.html.twig', [
    'posts' => $posts['data'],
]);

Trough this getPage() method in my controller I get paginated list of my data. Which is working. Than in the foreach() I am appending new key-value pair to that array.

When dumping $posts I get: IMAGE

When dumping $post from foreach, this is the output I get: IMAGE As you can see, the last pair, destinationName is added.

Then when dumping the same result in my twig template I get: IMAGE

As you can see, when template is rendered, it disappears.

My question is, that maybe it's overwritten? But I can not see why. Do I maybe need to append that filed in my query builder? But as I am adding the field after result is rendered, I suppose that should not be the case..

Any hints?

Maybe getDestinationName() will show something:

public function getDestinationName($posts)
{
    foreach ($posts as $postsData) {
        foreach ($postsData as $post) {
            $destinationName =  $this->getDestinationDetails(
                $post->getDestinationId(),
                $post->getAccountTokenId()
            );
            return $destinationName['full_name'];
        }
    }
}
malad85
  • 1
  • 2
  • Does this answer your question? [PHP foreach change original array values](https://stackoverflow.com/questions/15024616/php-foreach-change-original-array-values) – DarkBee Feb 08 '22 at 14:07
  • Not sure, because I do not need to change original value, just to add another one key-value pair. @DarkBee – malad85 Feb 08 '22 at 14:24

1 Answers1

0

It's not a good practice to mixe array with object and then add other stuff. The best thing you could do is this :

$posts = $this->entityManager->getRepository(Post::class)->getPage($listType, $page, $pageSize);

$destinationNames = [];
foreach ($posts['data'] as $post) {
    $destinationNames[$post->getPostId()] = $this->destinationService->getDestinationName($posts['data']);
}

return $this->render('posts.html.twig', [
    'posts' => $posts['data'],
    'destinationNames' => $destinationNames,
]);

I suppose here that $post->getPostId() is your unique identifier, if not, replace by the right identifier

And in your template you could do something like :

{% for post in posts %}
    // do your stuff
    {{ destinationNames[post.id] }}
{% endfor %}
jean-max
  • 1,640
  • 1
  • 18
  • 33