In this tutorial, I will explain on how to you can display error messages using CodeIgniter into your View from a Controller.
There are two kinds of approach of doing this. First, passing the data directly from Controller to View. Second, using flashdata.
This code is useful, for example, if you have a shopping cart application. Say you want to display an error message telling your visitor that the cart is empty.
First approach:
To do this, add the following in your Controller:
if (!$this->cart->contents())
{
$this->data['err_message'] = 'Your cart is empty!';
}
$this->load->view('templates/header', $this->data);
$this->load->view('bookings', $this->data);
$this->load->view('templates/footer');
err_message will become a variable once it is passed into your View called "bookings".
div id="infoMessage"><?php echo $err_message;?></div>
In your booking view, add the following code:
Second approach:
We will use set_flashdata function to display the error message when the page is being redirected.
if (!$this->cart->contents())
{
$this->session->set_flashdata('err_message', 'Your cart is empty!');
}
redirect('/bookings');
In your bookings page, add the following code:
<div id="infoMessage"><?php echo $this->session->flashdata('err_message');?></div>
flashdata is different on the first approach since it will only display the error when it was redirected from other page.