Codeigniter Flashdata - Not Displaying My Message - php

I am using this extension of the CI_Session Class. To create flash data and style them using TW Bootstrap. However when I go to pass the "Success" message to the view it's just not loading in at all.
I have had a good luck but no joy with it.
My Controller looks like this..
// Set form Validation
$this->form_validation->set_rules('title', 'Title', 'required|trim|is_unique[films.title]');
if($this->form_validation->run() == FALSE)
{
$data['page_title'] = 'Add New DVD';
$this->load->view('_partials/_header', $data);
$this->load->view('_partials/_menu');
$data['genres'] = $this->genre_model->get_genres();
$data['classification'] = $this->classification_model->get_classifications();
$this->load->view('create', $data);
$this->load->view('_partials/_footer');
}
else
{
// Insert into DB
$film_data = array
(
'title' => $this->input->post('title'),
'genre_id' => $this->input->post('genre'),
'classification_id' => $this->input->post('classification')
);
$this->film_model->create($film_data);
$this->session->set_success_flashdata('feedback', 'Success message for client to see');
redirect('dvd');
and my View is....
<?php $this->session->flashdata('feedback'); ?>
So when I insert a new item to the DB, The Model runs, The redirect runs but the "set_success_flashdata" doesnt.
The MY_session library is set to load automatically as per CI's default config.
How do I get this damn Flash Message to show ::( ?

It is not set_success_flashdata it is just set_flashdata.
Change in Controller :
$this->session->set_flashdata('feedback', 'Success message for client to see');
View is just as it is :
echo $this->session->flashdata('feedback');
Hope this helps you. Thanks!!

Although I fail to see the point of this particular extension, the answer is simple enough.
You are not echoing the data from the Session Library.
The correct way to echo flashdata is like so:
<?php echo $this->session->flashdata('feedback'); ?>

Related

Calling a MVC method is stopping my jQuery from outputting

(A) //The sigup.inc.php page
//Instantiating signup object.;after successfully linking the signup controller
$newPerson = new Signup_Contr($firstName, $lastName);
//Calling the signupUser() from the controller
$result = $newPerson->SignupUser();
//Now if I want to send any json object to ajax; for example:
$message = ['status' => 'error', 'message' => "Username already existed"];
echo json_encode($message);
//(B): The problem
whenever I include the calling MVC method in the sigup.inc.php:
$result = $newPerson->SignupUser();
The jQuery's
success property
do not output. And when I debug it in Chrome the watch window say:
response: not available
However, if I do not include this method my jQuery output works perfectly...
HELP will be much appreciated !

How to use Flash messages in fat free framework?

I am trying to make an small app so I have choosen Fat Free Framework. I need to show some messages based on successful or error. Suppose if I want to add an user then if successfully added show message that user has been added successfully or if not show error message that user cannot be added. I cannot figure it out. Here is my UsersController code
public function index(){
$user = new User($this->db);
$this->f3->set('users',$user->all());
//there should be a way to decide if its error message or success and after display,
//it shouldn't be displayed again for the same task.
//or may be it should be check in view file, I don't know where is the correct place
// to do it
$this->f3->set('page_head','User List');
$this->f3->set('view','users/list.htm');
}
public function create(){
if($this->f3->exists('POST.create')){
$user = new User($this->db);
$user->add();
//set session here to show in view file after redirect to list page
$this->f3->reroute('/users');
} else{
$this->f3->set('page_head','Create User');
$this->f3->set('view','users/create.htm');
}
}
My flash messages controller looks like this: https://github.com/ikkez/f3-flash/blob/master/lib/flash.php
To set a message i do:
if ($this->resource->updateProperty(array('_id = ?', $params['id']), 'published', true)) {
\Flash::instance()->addMessage('Your post was published. Hurray!', 'success');
} else {
\Flash::instance()->addMessage('This Post ID was not found', 'danger');
}
$f3->reroute('/admin/post');
To render the messages i include this template in my layout https://github.com/ikkez/fabulog/blob/master/app/ui/templates/alert.html which calls a function that dumps and clears all messages, so they will only be displayed once. You can also use the SESSION in a template token like {{#SESSION.flash}} and use it for <repeat> in the template.

Zend Framework 2 Flash Messenger returning no messages

I'm having a rather odd problem with flash messenger in ZF2. I'm using it in quite a simple scenario, save a 'registration complete' message after registering and redirect to the login page and display the message however the messages are never returned by the flash messenger.
In controller register action:
$this->flashMessenger()->addMessage('Registration complete');
return $this->redirect()->toRoute('default', array('controller' => 'user', 'action' => 'login'));
In controller login action:
$flashMessenger = $this->flashMessenger();
$mes = $flashMessenger->hasMessages();
$cur = $flashMessenger->hasCurrentMessages();
Both $mes and $cur are false (I tried both just to be sure). Can anyone shed any light on this?
I'm using ZF 2.2.2 and PHP 5.3.14. Session save handler is using the dbtable adapter and I have tried disabling this as well as setting the flashmessenger session manager to the use the same dbtable save handler with no result.
To use the FlashMessenger controller plugin, you need to add the following in your controller:
<?php
class IndexController extends AbstractActionController {
public function indexAction() {
$this->flashMessenger()->addMessage('Your message');
return $this->redirect()->toRoute('admin/default', array('controller'=>'index', 'action'=>'thankyou'));
}
public function thankyouAction() {
return new ViewModel();
}
}
Add the following to the thankyou.phtml view template:
<?php
if ($this->flashMessenger()->hasMessages()) {
echo '<div class="alert alert-info">';
$messages = $this->flashMessenger()->getMessages();
foreach($messages as $message) {
echo $message;
}
echo '</div>';
}
?>
It seems that your code is as it should be, there must be something tricky in the workflow.
In this case, you can debug the old way : try var_dump($_SESSION) to see if it is populated by your flashMessenger.
Use
echo $this->flashMessenger()->renderCurrent(...
instead of
echo $this->flashMessenger()->render(...
I also faced same problem for (login flashmessage after registration) I solved it in the following way
Apply a check on your layout page like
<?php if($this->zfcUserIdentity()) { ?>
<div id="flashMessageDiv" class="hide">
<?php echo isset($flashMessages) && isset($flashMessages['0']) ? $flashMessages['0'] : ''; ?>
</div>
<?php } ?>
That means layout flashMessageDiv is accessible only to the logined user . now on your login view file (login.phtml)
apply the following code
<?php $pathArray = $_SERVER['HTTP_REFERER'];
$pathArray = explode("/",$pathArray);
?>
<?php if ($pathArray[4] === 'register') { ?>
<div id="flashMessageDiv" class="hide">
<?php echo "User details saved successfully"; ?>
</div>
<?php } ?>
In the above code i used HTTP_REFERER which will simply give us the referer url details check if referer url is register then show falshmessage.
Hope it will help you.
The FlashMessenger is now an official view helper in ZF2 and can be easily integrated in every view / layout:
FlashMessenger Helper — Zend Framework 2 2.3.1 documentation - Zend Framework
It works with TwitterBootstrap3 too and there is an alternative configuration for your module.config.php.

Yii Frameworrk Ajax Link

My index post controller list all posts in the following way
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
)); ?>
My view _view has the ajax-link
<div id="comments"></div>
<?php echo CHtml::ajaxLink('List Comments', array('listComments'),
array('update' => '#comments'))?>
listComments is a function in my PostController
public function actionListComments()
{
$this->renderPartial('_comments',array(
'post'=>$model,
'comments'=>$model->comments,
));
}
When I click to the ajax link , nothing happens,
it points to localhost/blog/#
Can you help me please ?
The problem is actionListComments() method returns non-200 HTTP code because of undefined $model variable in it. Try something like this:
_view:
<div id="comments"></div>
<?php echo CHtml::ajaxLink('List Comments', array('listComments', 'id' => $data->id),
array('update' => '#comments'))?>
PostController:
public function actionListComments($id)
{
$model = Posts::model()->findByPk($id);
if($model !== null)
$this->renderPartial('_comments',array(
'post'=>$model,
'comments'=>$model->comments,
));
else
Yii::log('Unknown post with $id ' . $id, 'error');
}
First in actionListComments() you have a variable $model which you haven't instantiated.
Assuming you are getting the $model->id from the link it should change to:
<?php echo CHtml::ajaxLink('List Comments', array('listComments','id'=>$data->id),
array('update' => '#comments'))?>
Next, your actionListComments() should access the id, use this to load a model and its comments, and send this to the required view
public function actionListComments($id){
$model=$this->loadModel($id);
$this->renderPartial('_comments',array('model'=>$model));
}
There is no need to send $model->comments as we are already sending $model therefore we can access $model->comments.
many things could go wrong about that. As ajax calls cant be debugged with normal compnonents like
CVarDumper::Dump();
die();
Above code will not show you anything in the browser area. The best way to debug ajax calls is using inspectElement. Click on Network. Now when you click on ajaxLink it will show you whether the ajax request was sent successfully. It will be red if the request was unsuccessful. When you click on the request made. It will show you 3 tabs on right named Header, Preview, Response. As you want to render the page so the content-Type should be text/html.
As far as your code is concerned clearly you are using $model without instantiating it so it is returning error.
Read the error returned in your case.

codeigniter flashdata not clearing

I'm a newbie to codeigniter and I'm creating a project in which users are created and managed. here I'm using flashdata to display the temporary messages like "user created",etc.,
My code to set flash data is
$this->session->set_flashdata('message', 'User Created.');
In my view I called it as
$this->session->flashdata('message');
My problem is that when the user is created,flashdata is displayed and when i click home link the flash data is still available but when i click refresh/home again it disappears. I want it to be cleared when i click the home link for the first time itself. Is there a way to code it??.
Flashdata will only be available for the next server request, and are then automatically cleared.
if($user_created)
{
$this->session->set_flashdata('success', 'User created!');
redirect('login');
}
else
{
redirect('register');
}
if you want to clear set_flash in controller or another view file, then you can use this simple code.
$this->session->set_flashdata('error', 'User not found...'); //create set_flash
unset set_flash
//echo "<pre>"; print_r($_SESSION); die; //for check
if(isset($_SESSION['error'])){
unset($_SESSION['error']);
}
You should redirect after user created. Then when next time you click on home link it will not appear, try this,
$this->session->set_flashdata('message', 'User Created.');
redirect(base_url().'home.php');// you can change accordingly
The flashdata is supposed to display once.
And it gets disappears on page refresh.
So, if you redirect the page to another, it should work.
If you do not refresh the page, you can do it through jQuery.
Say your div displaying flash:
<div id="flash-messages">Success Message</div>
Write jQuery:
<script type="text/javascript">
$(function(){
$("#flash-messages").click(function(){$(this).hide()});
});
</script>
You must redirect the page somewhere after $this->session->set_flash('item','value');
Example:
if ($this->form_validation->run() == FALSE){
$this->session->set_flashdata('error',validation_errors());
redirect(base_url().'user/login');
}
else{
$this->session->set_flashdata('success','Thank you');
redirect(base_url().'user/login');
}
Usually developer make a mistake when they submit data to same page. They set flash data but forget to redirect.
You can use a Ajax framework for automatically hide the flash message.Also their contains all of the flash operation.
You can get more information from here.
https://github.com/EllisLab/CodeIgniter/wiki/Ajax-Framework-For-CodeIgniter
If nothing else helps, just extend the Session library and add a clear_flashdata function.
<?php defined('BASEPATH') or exit('No direct script access allowed');
// application/libraries/Session/MY_Session.php
class MY_Session extends CI_Session
{
public function __construct(array $params = array())
{
parent::__construct($params);
}
/**
* Clear flashdata
*
* Legacy CI_Session compatibility method
*
* #param mixed $data Session data key or an associative array
* #return void
*/
public function clear_flashdata($data)
{
$this->set_userdata($data, null);
}
}

Categories