views:

30

answers:

1

Well,

It's a beginner's question but I really don't know what is the best way. I have a basic CRUD (Create, Retrieve, Update and Delete) in my project and I'd like to output some message if succeeded or not in a div inside the same page.

So, basically, I have a form which action is set to the same page and I have a div #statusDiv below this same form which I'd like to output something like Register included with success.

What is the best way for doing this?

  • Set a flag in the controller $this->view->flagStatus = 'message' then call it in the view?

Just to make it more clear. It's my code:

//IndexController.php indexAction()

...

//Check if there's submitted data
if ($this->getRequest()->isPost()) {
    ...
    $registries->insert($data);
    $this->view->flagStatus = 'message';
}

Then my view:

....
<?php if ($this->flagStatus) { ?>   
    <div id="divStatus" class="success span-5" style="display: none;">
        <?php echo $this->flagStatus; ?>
    </div>
<?php } ?>
....
+2  A: 

In this situation since you're redirecting, the $this->view->flagStatus will be lost. Instead what you should use is the flashMessenger Action helper:

http://framework.zend.com/manual/en/zend.controller.actionhelpers.html

basically you use it just like you are currently, except you'd change:

$this->view->flagStatus = 'message';

to

$this->_helper->flashMessenger->addMessage('message');

after this you'll need to send the flashMessenger object to the view. You should do this in a place that gets executed on every page request so you can send messages to any page:

$this->view->flashMessenger = $this->_helper->flashMessenger;

and then change your view to:

<?php if($this->flashMessenger->hasMessages(): ?> 
    <div id="divStatus" class="success span-5" style="display: none;">
        <?php $messages = $this->flashMessenger->getMessages(); ?>
        <?php foreach($messages as $message): ?>
        <p><?= $message; ?></p>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

Hope this helps!

Aaron
yeahh! this helped a lot! thx for the answer.. I just made a mistake, I didn't intent to redirect. Still, is it the best way to do that? How should I do it without the redirect?
Rodrigo Alves
I prefer to redirect after a form post because it clears out the post request and allows the user to refresh the page without double submitting the form.If you didn't want to redirect, you could use the method you described, it should work okay.
Aaron