Tarek EZZAT
Tarek EZZAT

Reputation: 353

Symfony 4 UndefinedMethodException addFlash

I have a strange error in Symfony 4

files are "inspired" by symfony documentation.

Here is my service file

<?php
namespace App\Services;

class MessageGenerator
{
    public function getHappyMessage()
    {
        $messages = [
    'You did it! You updated the system! Amazing!',
    'That was one of the coolest updates I\'ve seen all day!',
    'Great work! Keep going!',
];

    $index = array_rand($messages);

    return $messages[$index];
}
}

Here is my controller

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use App\Services\MessageGenerator;

class DefaultController
{
private $message;

public function __construct(MessageGenerator $messageGenerator)
{

    $message = $messageGenerator->getHappyMessage();
    $this->addFlash('success',$message);
    // ...
}


public function getMessage(){
    return $this->message;
}

public function index()
{
    return new Response("<p>Hello !</p> ");
}
}

When I run this code, I get an error : Attempted to call an undefined method named "addFlash" of class "App\Controller\DefaultController".

Any idea?

Upvotes: 0

Views: 1002

Answers (2)

zerkms
zerkms

Reputation: 254956

Now it has moved to the ControllerTrait. So simply put

use \Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;

somewhere after your controller class declaration begin:

class DefaultController
{
    use \Symfony\Bundle\FrameworkBundle\Controller\ControllerTrait;

    private $message;
...

Upvotes: 0

ehymel
ehymel

Reputation: 1391

Since addFlash is a helper method, you need to extend the AbstractController to gain access to it:

class DefaultController extends AbstractController

See the docs.

Upvotes: 1

Related Questions