How do I display result or error messages in CodeIgniter application

Sometimes we need to display general messages or error messages to the user noticing about certain action, for example on success or failure.

Imagine you are submitting a form and then creating or updating the data in the database. You may be interested in noticing the user about the result for that action.

This is the way I use to display general messages (and error messages) in CodeIgniter application.

The result

This is how my message looks.

codeigniter-display-message

How to display the message?

Now, in order to display that information message, I do the following:

First, when submitting the form, after validating it, in the controller I call the model function that will save the entity (license in this case). I make sure that model function returns a result, and FALSE result in case of error (I usually return an array result on success with an ID element with the last inserted identifier if the result was an insert, or the just updated entity identifier if it was an update, but that is out of this article’s scope).

Controller

Imagine we are calling the following method in the controller:

$result = $this->license_model->create_or_update_license($agent_id, $state, $data);

Then, we need to see if that was an error or not. Based on that result, I will use CodeIgniter’s set_flashdata function in the Session library, as follows:

if ($result)
{
	$this->session->set_flashdata( 'message', array( 'title' => 'License created', 'content' => 'License has been saved sucessfully', 'type' => 'message' ));
	redirect('agent/licenses');	

} else
{
	$this->session->set_flashdata( 'message', array( 'title' => 'License error', 'content' => 'License could not be saved', 'type' => 'error' ));
	redirect('agent/licenses');
}

Once the Flash message has been set, I redirect the user to the form or a list of results. That is needed in order to get the flash working (you cannot just load the view in this case… well, you can but this method will not work in such case). When comparing $result TRUE or FALSE, please notice the different value for type. I am using type=message for successful messages, and type=error for error mesages.

View

In the view, just above the form, I use this snippet.



<?= @flash_message() ?>

To keep it simple, I just added @ to avoid any error message, but probably if you are looking for a better coding practice and you may not do that.

A Helper

Then, I put this flash message function as a helper function, so it is available when calling from the view.


function flash_message()
{
	// get flash message from CI instance
	$ci =& get_instance();
	$flashmsg = $ci->session->flashdata('message');

	$html = '';
	if (is_array($flashmsg))
	{
		$html = '<div id="flashmessage" class="'.$flashmsg[type].'">
			<img style="float: right; cursor: pointer" id="closemessage" src="'.base_url().'images/cross.png" />
			<strong>'.$flashmsg['title'].'</strong>
			<p>'.$flashmsg['content'].'</p>
			</div>';
	}
	return $html;
}

jQuery part

Finally, I added a simple effect to slide down and blink the message box, and adding the close functionality with a simple jQuery function. You can do something like this. Of course, you can modify it or just avoid using the jQuery effect if it is desired.


// first slide down and blink the message box
$("#flashmessage").animate({top: "0px"}, 1000 ).show('fast').fadeIn(200).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

Some CSS styling

Finally, just add some CSS styling for #flashmessage, using message or error class names.


.message{
    border:1px solid #CCCCCC;
    width:300px;
    border:1px solid #c93;
    background:#ffc;
    padding:5px;
    color: #333333;
    margin-bottom:10px;
}

Enjoy it.

Related searches:

  • codeigniter error to email
  • codeigniter flash message
  • codeigniter error message
  • codeigniter error messages
  • codeigniter set_flashdata
  • codeigniter message
  • codeigniter messages
  • flash message in CodeIgniter
  • flash message codeigniter
  • codeigniter flash messages
  1. Benoa says:

    Smart approach! Though the view snippet is missing so is the jquery to close the message. :/

    I’ll assume it was $(“#closemessage”).click( function () { $(this).parent(“div”).fadeOut(“slow”); });

  2. ridho says:

    hei. i found this tutorial.
    i have applied this.and it works. .
    and for the close button i had to paste the benoa code.
    but i need the cross.png icon. had to create it by myself.
    it d be nice if you provide it here.
    hehehe..

  3. brad greenspan says:

    isn’t it easier to use session flash data?

  4. admin says:

    Isn’t this solution using session flash data? Basically what this is showing is the stylized way to achieve that. But in fact, it uses session’s set_flashdata.

  5. Paul says:

    Very elegant solution! Will be using this in my future projects.

  6. anuser says:

    I was searching for something like
    “how to display custom messages (error or success) using a unique view file”
    and you answered !
    Now i’m just looking at a similar way but without using session!
    anyway thanx for the great help !!

  7. admin says:

    Thanks for your message @anuser, we are glad you found what you was looking for.

  8. NomikOS says:

    Well done. An one-stop solution. Exactly what I need. THX,.-

  9. J.T. says:

    This is almost exactly the method I developed for myself, but I’ve discovered a problem with it (and found this page while googling for a solution to it) — when a form fails to validate, I want to use the set_value function to display the previously submitted values to the user. If you use a redirect, set_value no longer works.

    Have you found a workaround for that, or has it not been an issue for you?

  10. admin says:

    Hmm. I am not sure to understand your question, but do you really need to use “redirect”? If it is a form, then you likely will POST the form. Redirect won’t be used until the form is processed properly and then you can redirect to another page. I think you are trying to use a redirect where it shouldn’t be used…

  11. J.T. says:

    I’ve got my error-handling built around redirecting-with-a-message — I want to do form-validation errors the same way but I think I’m going to have to retool it.

  1. [...] How to Display Result Messages in CodeIgniter [...]

Leave a Reply