Zend flash messenger - php

I have a form and the submit button check if true or false.
If it's true redirect to another page.
If it's false stay on the same page and print the error message.
The error message is print out with a flash messenger.
But, in some case it doesn't print in the first try when submit is false, it always print out on the second click.
Did I did something wrong?
And also, is there a way to set difference flash messenger name? Because, on my others pages that have flash messenger, print out the error when page is refreshed.
Here's the code:
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
$this->view->messages = $this->_helper->flashMessenger->getMessages();
}
}
HTML:
<center>
<div style="color:red">
<?php if (count($this->messages)) : ?>
<?php foreach ($this->messages as $message) : ?>
<div id="field_name">
<strong style="text-transform:capitalize;">Email </strong>
- <?php echo $this->escape($message); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</center>

flashmessenger is really designed to be used on a redirect of some kind, so any message you see probably comes from the prior action's execution. Your current code would not flash any message during the first 'post'.
you may have some luck if you try something like:
public function init()
{
//This will catch any messege set in any action in this controller and send
//it to the view on the next request.
if ($this->_helper->FlashMessenger->hasMessages()) {
$this->view->messages = $this->_helper->FlashMessenger->getMessages();
}
}
public function someAction()
{
if(isset($_POST['submit'])) {
// code to inputfields
if(true) {
//redirect to some page
} else {
// print the flash error on the same page
$this->_helper->flashMessenger->addMessage(" This email is already taken");
//will redirect back to original url. May help, may not
$this->_redirect($this->getRequest()->getRequestUri());
}
}
}
Here's an action I coded that demonstrates what you seem to be attempting.
public function updatetrackAction()
{
//get the page number
$session = new Zend_Session_Namespace('page');
$id = $this->getRequest()->getParam('id');
//get the entity object
$model = new Music_Model_Mapper_Track();
$track = $model->findById($id);
//get the form
$form = new Admin_Form_Track();
$form->setAction('/admin/music/updatetrack/');
//test for 'post' 'valid' and update info
if ($this->getRequest()->isPost()) {
if ($form->isValid($this->getRequest()->getPost())) {
$data = $form->getValues();
$newTrack = new Music_Model_Track($data);
$update = $model->saveTrack($newTrack);
//add message
$this->message->addMessage("Update of track '$update->title' complete!");
//redirects back to the same page number the request came from
$this->getHelper('Redirector')->gotoSimple('update', null, null, array('page' => $session->page));
}
} else {
//if not post display current information
//populate() only accepts an array - no objects -
$form->populate($track->toArray());
$this->view->form = $form;
}
}

Related

Flash messages with sessions in PHP

I work on a project in PHP which does not use any kind of a framework for PHP. I come from Yii background and I've used:
Yii::app()->user->setFlash('flash_name', 'Flash value');
And checked it with:
Yii::app()->user->hasFlash('flash_name');
To check if it is present and if it exists, and to get the value of it I used:
Yii::app()->user->getFlash('flash_name', 'Default Flash value');
For now, I wrote these functions to set, check and get flash:
function set_flash($flash_name, $value) {
$_SESSION['flashes'][$flash_name] = $value;
}
function has_flash($flash_name) {
return isset($_SESSION['flashes'][$flash_name]) ? true : false;
}
function get_flash($flash_name, $default_value = null) {
if(has_flash($flash_name)) {
return $_SESSION['flashes'][$flash_name];
}
return $default_value;
}
However, when I use it in my post.php like this:
set_flash('success', true);
And check it in my index.php like this:
<div class="container">
<?php if(has_flash('success') && (get_flash('success') === true)): ?>
<div class="alert alert-success">
<h4>Success!</h4>
<hr />
<p>You have successfully posted new content on your website. Now you can edit or delete this post.</p>
</div>
<?php endif; ?>
</div>
whenever I refresh the page, the message would still appear there.
How can I remove the flash after it's been used or invoked?
Add a new line to get_flash:
function get_flash($flash_name, $default_value = null) {
if(has_flash($flash_name)) {
$retVal = $_SESSION['flashes'][$flash_name];
// don't unset before you get the vaue
unset($_SESSION['flashes'][$flash_name]);
return $retVal;
}
return $default_value;
}

CakePHP form not posting

I am working on a page that can update the sales agent on a specific order.
I made the list of options and a dropdown list is created.
Heres in the controller:
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is("post")) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
Heres the view:
echo $this->Form->create("Order");
echo $this->Form->input("OrderID");
echo $this->Form->input("UserID");
echo $this->Form->submit("Submit");
echo $this->Form->end();
When I submit the data, it appears that the data is saved, (the flash message is set).
However, when I then preset the fields with data that is already in the database, all the sudden it doesn't even post. (I put a debug after the reques->is("post) condition which doesnt show up after I submit).
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is("post")) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
if (!$this->request->data) {
$this->request->data = $order;
}
The input fields are correctly pre filled, but now the form doesn't even post.
Does anybody know whats wrong?
Thanks!
Update your controller code to:
$order = $this->Order->read(null,$id);
$this->set("order",$order);
if ($this->request->is('post') || $this->request->is('put')) {
if($this->Order->save($this->request->data)) {
$this->Session->setFlash("Sales Agent Updated");
}
}
Now put a debug after the reques->is('post') condition which will show what you need to show.

Using flashdata while posting same controller twice in Codeigniter

I am trying to submit a EDIT form which edits Users Academics Details,
These Details have unique id in DB and my Code in Short Looks like below :
class edit extends ci_controller
{
function user_academics($id = NULL)
{
if(isset($id) == FALSE) //if link is ./edit/user_academics
{
$id = NULL;
$link = site_url('profile');
show_error("Invalid Page Request! <a href='$link' Go to Profile </a>");
}
$user_id = $this->session->userdata('user_id');
$data['fill'] = $this->edit_model->get_user_academics($id);
if($user_id != $data['fill']['user_id']) // check if logged in user is accessing his record or others
{
$link = site_url('profile');
show_error("This is an Invalid Request ! <a href='$link'>Go to Profile </a>");
}
else // actual work starts here
{
$this->session->set_flashdata('ua_id',$id); // update_academics will get this data
$this->load->view('edit/edit_3_view',$data);
}
}
function update_academics()
{
$ua_id = $this->session->flashdata('ua_id'); // flash data used here .
if( !$ua_id )
{
show_error('Sorry, This request is not valid!');
}
$academics = array(
// All post values
);
$this->edit_model->update_user_academics($academics,$ua_id);
//print_r($academics);
redirect('profile');
}
}
Now the problem is
- If I open two different records to edit, then It will set only one Session Flash value.
- And No matter what I edit , the existing values of the last flash value gets updated.
Please Suggest me another way or Correct me if I am wrong in above code . Thanks
save that flashdata in array, like:
$myArr = array('value 1', 'value 1');
//set it
$this->session->set_flashdata('some_name', $myArr);
And in view:
$dataArrs = $this->session->flashdata('some_name');
//loop thru $dataArrs to show the flashdata
Flash data is simply like variable which is available only in next request, you can bypass this behavior by using two different keys with record id in it, so that when you use flash data for showing message you can access key with particular record id.

CakePHP Login element

Maybe a simple question but how do I change my login box after logging in. Such as 'Welcome user'
I can't find good examples ...
My code looks like this
users_controller
function login {
}.. with login element
See here as example: http://groups.google.com/group/cake-php/browse_thread/thread/56ff0ce37fb06a30
You have 2 options:
Depending of your login state, choose another element, like:
function login() {
if ($isUserLoggedIn == false) {
// render login element
} else {
// render welcome element
}
}
this is more bad option In login element add logic like:
if (!$isUserLoggedIn) {
// echo html and code for login
} else {
// echo html and code for welcome
}
I suppose that you want an action/view that can be rendered by both logged and not logged in users.
Similar to riky's the following code might help you
In your controller:
//check if user is logged in and set $user_details variable in the view
if($this->Auth->User()){
$user_details = $this->Auth->User();
}
$this->set(compact('user_details'));
In your view:
<? //check if $user_details variable is set (user is logged in) and display the correct element
if(isset($user_details){
echo $this->element('welcome_box',array('user_details'=>$user_details));
}else{
echo $this->element('login_box');
}
?>

cakephp session can't be written

Controller
function login() {
// Don't show the error message if no data has been submitted.
$this->set('error', false);
// Does not render the view
$this->autoRender = false;
// If a user has submitted form data:
if(!empty($this->data)) {
$someone = $this->Student->findByStudentEmail($this->data['Student']['email']);
if(!empty($someone['Student']['student_pwd']) && $someone['Student']['student_pwd'] == $this->data['Student']['password']) {
$this->Session->write('eyeColor', 'Green');
$this->Session->write('Student', $someone['Student']);
// session information to remember this user as 'logged-in'.
echo "success";
} else {
echo "failed";
}
}
function main(){
$this->set('students', $this->Student->find('all'));
$this->set('eyeColor', $this->Session->read('eyeColor'));
// Render the specified view
$this->render('/pages/main');
}
view
main.ctp
<?php print $eyeColor; ?>
<?php echo $session->read('eyeColor') ?>
It's in the manual: http://book.cakephp.org/view/1466/Methods
Admittedly, though, it's not very clear. Maybe I'll submit an update.

Categories