Forms and success output
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 } ?>
....
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!
精彩评论