We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

flash / flashMessages - type - how to get it ?

Hello guys,

I have a custom flashSession class with this contructor:

    public function __construct()
    {
        parent::__construct();
        $this->setAutomaticHtml(false);
        $this->setImplicitFlush(false);
    }

I want to assing message to the view, so they can be used in a javascript environment. This is how i am doing it:

    public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
    {
        $flash = array();

        foreach ($this->flashSession->getMessages() as $message) {
            $flash[] = $message;
        }

        $this->view->flashMessages = $flash[0];
    }

View:

<html>
...
<script>
var app = {
    //...
    'flashMessages' : []
    //...
};

{% if flashMessages %}
    {% for message in flashMessages %}
        app.flashMessages.push("{{ message }}");
    {% endfor %}
{% endif %}
</script>

</html>

I need to know the type of the message (error, alert, success, etc), so i can render the correct JS flash method notification.

  • The output of the messages, are raw text, not html formatted. And i don't want to use the HTML format.

Any thoughts ? Thanks.



5.2k
Accepted
answer

Try this:

    public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher)
    {
        $flash = array();

        foreach ($this->flashSession->getMessages() as $type => $message) {
            if (!isset($flash[$type])) {
                $flash[$type] = array();
            }
            $flash[$type][] = $message;
        }

        $this->view->flashMessages = $flash;
    }


51.2k
edited Jun '14

Nevermind. i found the solution:

  1. I overwrite the methods. Eg:
    public function error($message)
    {
        $format = "{'type':'error', 'message':'".$message."'}";
        return parent::error($format);
    }
  1. I render the view with:
{% if isset(flashMessages) %}
    {% for key, message in flashMessages %}
    app.flashMessages[{{ key }}] = {{ message }};
    {% endfor %}
{% endif %}
  1. An voila ! In JS i use:
            if (app.flashMessages.length > 0) {
                $.each(app.flashMessages, function(key, data){
                    console.log(data);
                })
            };

That's it ;)



51.2k

Ha ha ha :)) Nice finding Marcin :)) Thank you. Naver thought about using key => value :)). So accepted answer would be Marcin's . My answer works as well.



51.2k

Ah. Now we can use

$this->view->flashMessages = json_encode($flash, JSON_FORCE_OBJECT);