Search code examples
phpsymfonydoctrine-ormentitysymfony4

Symfony - findOneOrFail returns array message


In my Symfony service I wanted to add small edit so I decided it's better to do it inside the class.

In my controller I am getting storyId (it's not table ID, it's a string with different chars) from my Request like:

 $story = json_decode($request->getContent(), true);
 $storyId = $story['storyId'];

 $freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
 $story->freeStoryName($freeStoryName);

 return $this->json(["message" => "SUCCESS"]);

And In my Entity class I handle it like:

public function freeStoryName(Story $story): Story
{
    $this->setPreviousStoryName($story->getStoryName());
    $story->setStoryName(null);
}

And I get the error message:

Call to a member function freeStoryName() on array

I know what the message means but do not get it? It's findOne() method.. And other question will be, do I need flush() method in the Entity class like I had in a service?


Solution

  • You are using freeStoryName on $story which is an array (json_decode($request->getContent(), true);)

    You need to use your method with your result :

     $story = json_decode($request->getContent(), true);
     $storyId = $story['storyId'];
    
     $freeStoryName = $this->storyRepo->findOneOrFail(['storyId' => $storyId]);
     $freeStoryName->freeStoryName($freeStoryName);
    
     return $this->json(["message" => "SUCCESS"]);
    

    If you feel that it's a little weird to do it this way, you could change your method to:

    public function freeStoryName()
    {
        $this->setPreviousStoryName($this->getStoryName());
        $this->setStoryName(null);
    }
    

    And use it:

    $freeStoryName->freeStoryName();