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.
Related
In my contact.php page, I am sending emails to admin and user after passing the validation. The code looks something below:
// If any validation error occurs
if(count($errors) > 0)
{
// show error messages
}
else
{
// sending emails to admin and user
set_flash_msg('msg', 'Thank you for contacting us.', 'success');
redirect_to('contact');
}
But the code in else part related flash message doesn't work. If I put this code in if part then it works without any issue. The function set_flash_msg() is responsible to create session based flash message. Its code is below:
// Set flash message
function set_flash_msg($name, $msg, $class)
{
global $name;
if(empty($_SESSION[$name]) && empty($_SESSION[$name . '_class']))
{
$_SESSION[$name] = $msg;
$_SESSION[$name . '_class'] = $class;
}
}
To display this message, another function is called below the above code as:
// Show flash message
get_flash_msg();
There is no issue regarding session setting because in if part, it works fine. The same logic and coding flow is used in my backend too where I set flash message when a new page is added and show the flash message on page listing page.php. If it works at there then why it doesn't work on my front-end contact.php page? Any idea?
In my contact.php page, I am grabbing the form values particularly "name" as:
// Preparing form variables
$name = isset($_POST['txtname']) ? $db_obj->sanitize_input($_POST['txtname']) : '';
The local variable $name conflicts with global variable $name in set_flash_msg() function. Changing $name to $uname in above code solved the problem.
first of all sorry for my bad english.
The problem is as follows:
I try to do add and edit post in Blog system.
My pseudocode:
private function getPostForm()
{
$form=$this->createFormBuilder()
->add(...
}
public function addPost()
{
$form=$this->getPostForm... (is a createFormBuilder
// form to create new post
// display form to add - send to updatePost
}
public function editPost()
{
$form=$this->getPostForm... (is a createFormBuilder
// get post id and display form to edit post
// send to updatePost
}
public function updatePost()
{
// get data from post and validate
$form->bind(...
// if validate is true => save
if($form->isValid())....
// if not => get errors and display
else {
// redirect and display errors and post data
}
My problem - when form is not valid, I would like redirect user to add/edit post and display errors thanks to user can't refresh page (eg. F5 key) when data will be sent and not valid.
How to do it correctly?
Maybe, you should do like this. If all is correct do update and redirect, if validation fail display view again
public function updatePost()
{
....
if($form->isValid()){
//yours update logic
return $this->redirect(..);
}
return $this->render('create.html.twig', array(
'form' => $form->createView();
));
}
I have a method in CI which basically adds a user to a table - if any form validation occurs it reloads the view - if successful it reloads the view to show that the user was added successfully. As seen below:
public function loadPeopleView(){
//loads unit page view
$this->load->model('people_model');
$people['people'] = $this->people_model->getPeople();
$this->load->view("header");
$this->load->view("people page/people_view", $people);
$this->load->view("footer");
}
public function addPerson(){
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
if($this->form_validation->run()){
$this->load->model('');
$this->people_model->addPerson();
$this->loadPeopleView();
} else{
//if validation fails - returns the peopl view this display error messages
$this->loadPeopleView();
}
}
my issue is when someone adds a person the browser remains on:
localhost/peoplecontroller/addperson
if the user keeps refreshing the page - loads of people will continue to be added in - is there anyway I can put the page back to:
localhost/peoplecontroller/
without having to use a redirect as I still want any error messages from the form validation to appear
I am only giving you an example please arrange according save and return functionality
public function addPerson(){
$this->load->model('people_model'); // load model
// validation
$this->form_validation->set_rules('personName', 'personName', 'required|min_length[6]|max_length[150]|trim|xss_clean');
$this->form_validation->set_rules('personPet', 'personPet', 'required|trim|min_length[3]|max_length[30]|xss_clean');
// check validation not clear
if ($this->form_validation->run() == FALSE) {
//if validation fails - returns the peopl view this display error messages
// also set error dat back
// setting up send back values to view
$this->data['personName'] = $this->input->post('personName');
$this->data['personPet'] = $this->input->post('personPet');
// get this->data values as a variable in view like $personName
// load view
$this->load->view("header");
$this->load->view("people page/people_view", $this->data);
$this->load->view("footer");
}
else{ // after validation success
// do your saving db stuff and set success message in session flash and redirect to
$this->people_model->addPerson();
// get and show message flash in your view
$this->session->set_flashdata('message', 'Please check card details and try again');
redirect('results', 'refresh');
}
}
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);
}
}
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'); ?>