开发者

Remembering data when redirecting

开发者 https://www.devze.com 2023-04-05 15:59 出处:网络
I have an app in Symfony which generates many messages. Each action in the module can generate a message(s) stored in array. Last added messages should be displayed in any view (so I\'m calling the fu

I have an app in Symfony which generates many messages. Each action in the module can generate a message(s) stored in array. Last added messages should be displayed in any view (so I'm calling the function in layout.php, in order to have messages displayed in every view template). Many actions redirects (by redirect() function; I won't use forward() ) to another actions after setting message.

So the scheme is following. - Action A: set message, redirect to Action B. - Action B: display view (and layout of course as well).

When I don't use redirect(), everything works fine. But when I set the message ($my_array[] = "new message"), array seems to "die" (is empty) just after redirect('same_module/another_action').

The problem is:

How to set data (variable) in one action, which will be "accessible" in another action AFTER redirection ( redirect() ). I noticed that when I'm using forward(), variables are accessible, but when I use redirect(), all variables seems to be empty.

I even created my_class and put their functions to process (add, display) messages in lib directory, thinking that at least outern file will remember my messages (in array). But actually nothing changed - array seems again to be empty after redirection (count($messages_array) = 0 after redirect() ).

It开发者_高级运维's really weird to me. Any solution to this?


The reason it works with forward but not redirect is because redirect asks the browser to go to a new url (make a new http request), but forward does it internally (within symfony).

If you only need to display these messages once I suggest the flash functionality of symfony's myUser class, which gets cleared after the very next request. Set it in the action like:

$this->getUser()->setFlash("message", "blahlahblah");

then in your template you can call $sf_user->hasFlash("message") to see if the user has a flash of a specific type (in the example: message), then get it via $sf_user->getFlash("message"). A longer example:

<?php if ($sf_user->hasFlash("message")): ?>
  <div class="message">
    <?php echo $sf_user->getFlash("message) ?>
  </div>
<?php endif ?>

For detailed information on how the flash works see the docs.


How to set data (variable) in one action, which will be "accessible" in another action AFTER redirection ( redirect() ).

You should use symfony's user session :
- http://www.symfony-project.org/gentle-introduction/1_4/en/06-Inside-the-Controller-Layer#chapter_06_user_session

0

精彩评论

暂无评论...
验证码 换一张
取 消