Search code examples
phpsymfonydoctrinesymfony4

Symfony - Call to a member function getDestination() on string


In my Symfony project I am returning all objects with Doctrine query builder defined with Paginator.

When dumping $posts['data'], response is on the image: IMAGE

When entering the loop and dumping first result, this is what I get: IMAGE

I want on each array object to assign new key-value pair. Every array object has destinationId (you can see on the image), and I have a method that searches for the name by that param. I want to assign that new value to every object in foreach.

Code:

$posts = $this->entityManager->getRepository(Post::class)->getPage();

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

Error is:

Call to a member function getDestinationId() on string

This is very odd as this field has entity type defined as string and also when dumping

dump($post->getDestinationId()); 

I get: "107869901061558" which is string.


Solution

  • It's because you override you $postsData variable. You need to use a different variable to store your $destinationName like this :

    $posts = $this->entityManager->getRepository(Post::class)->getPage();
    $destinationNames = [];
    
    foreach ($posts['data'] as $postsData) {
      foreach ($postsData as $post) {
        $destinationName =  $this->destinationService->getDestinationNameById(
          $post->getDestinationId()
        );
        $destinationNames[$post->getId()] = $destinationName;
      }
    }
    

    Like this, you could send $destinationNames to your template and find the right $destinationName thanks to the index.