Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter flashdata - am I using it correctly?

I learned about flashdata and decided to use it to display messages based on database interactions.

For example if no rows are affected I want to display Post id is invalid or does not exist!

In my model

function delete_post($post_id)
    {
        $this->db->where('user_id', $user_id);
        $this->db->where('post_id', $post_id);
        $this->db->delete('posts'); 

        if ($this->db->affected_rows() == 0) 
        {
            $this->session->set_flashdata('result', 'Post id is invalid or does not exist!');
            redirect('/posts/management');
            return FALSE;
        }
        else
        {

            redirect('/posts/management');
            return TRUE;
        }                   
    }

and in my view

if ($this->session->flashdata('result') != ''): 
    echo $this->session->flashdata('result'); 
endif;

This seems to work fine but there is no example in the CI documentation how to pass flashdata between MVC. I'm concerned.. Am I doing this correctly?

edit: I seem to have left FALSE and TRUE from a prior attempt. I probably won't need that.

like image 251
CyberJunkie Avatar asked Jun 11 '11 00:06

CyberJunkie


3 Answers

Session data is available anywhere in your application, at any time. Calling it directly from a view file is proper, and so it setting it in a Controller.

There's no need at all to pass it as data with $this->load->view() - it's redundant. Why assign it to the flashdata in the first place in that case?

The way you're doing it is correct.

EDIT: I just saw you are setting it in the Model instead of Controller - which is highly debatable. I would suggest returning a value from your Model call, and setting the message based on it in your Controller instead.

like image 161
Wesley Murch Avatar answered Nov 16 '22 17:11

Wesley Murch


$myArr = array('value 1', 'value 1');

$this->session->set_flashdata('myArray', $myArr);

In the view,

print_r($this->session->flashdata('myArray'));
like image 23
Sumith Harshan Avatar answered Nov 16 '22 15:11

Sumith Harshan


I just save it in an array and pass it to the view :)

 $data['wow_list'] = $this->Wow_model->getWow($uid);

 $this->session->set_flashdata('message', 'Done. You have added new task.'); 

 $data['flash_message'] = $this->session->flashdata('message');


 $this->load->view('wow/index', $data);

View

<?= $flash_message ?>

Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function.

http://codeigniter.com/user_guide/general/views.html

like image 2
Vamsi Krishna B Avatar answered Nov 16 '22 17:11

Vamsi Krishna B