not able get flashdata in CodeIgniter - codeigniter

Here is my controller code
function index() {
echo $this->session->flashdata('message');
$this->load->view('categoryView');
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
$message = 'Category Name is used by the product. Please change them to another category!';
}
else {
$category_id = $this->product_category_model->delete($category_id);
$message = ($category_id) ? 'Category Deleted Successfully' : 'Failed to Delete Category';
}
$this->session->set_flashdata('message', $message);
redirect('category', 'refresh');
}
After calling the delete function the flashdata has to be set and retrieve that value in index() function of the same controller but I can't.
Am also tried the $this->session->keep_flashdata('message'); before redirect to index function. But still am not get any value in index function.
Also changed $config['sess_expire_on_close'] = FALSE; to $config['sess_expire_on_close'] = TRUE; Still am not get the result.
I am wasted more time(nearly half day). Please anybody help to retrieve the flas data in codeigniter.

There are several probabilities:
1- Check your browser cookie. See if it allows cookies or if any other extension is intervening.
2- Refresh might not send the browser a new request (which thus mean a new URL). Try it for another controller see if it make any change
3- hard code the set_flashdata() with hard-coded value than a variable. set_flashdata("message", "Thank you");

In codeingitor you cannot echo anything in controller.
You have to set in $this->session->flashdata('message'); in view file not in index() function of controller
Try again by putting $this->session->flashdata('message'); in "categoryView" file where you want to display flash message.

You could try:
function set_flashdata_notification($notify_type, $msg, $error_code = null)
{
$ci =& get_instance();
$flashdata_data = set_notification_array($notify_type, $msg, $error_code);
$ci->session->set_flashdata($flashdata_data);
}
function delete() {
$products = $this->item_model->get_category_id($category_id);
if (count($products)) {
set_flashdata_notification('Category Name is used by the product.','Please change them to another category!');
redirect('path_to_view/view','refresh');
}

Related

How to use session_data in codeigniter throughout Website without including in particular view

Is there any other best way to use session_data in website.
How i set session in my project:
$sess_array = array('id' => $row->user_id,'name'=>$row->user_name,'email'=>$row->email,'condition'=>'','balance'=>$row->balance,'did_alloted'=>$row->did_alloted,'create_date'=>$row->create_date);
$this->session->set_userdata('logged_in', $sess_array);
when it comes to controller:
$data['id'] = $session_data['id'];
$data['name'] = $session_data['name'];
$data['email'] = $session_data['email'];
$data['balance']=$session_data['balance'];
$data['did_alloted']=$session_data['did_alloted'];
$data['create_date']=$session_data['create_date'];
$this->load->view('san-reception', $data);
and in my view. I use <?php echo $name ?> to get session_data.
So is there any method by which i can directly access session_data in view without including as $data.
$this->session->userdata('logged_in'); will be available directly in views and hence you just need to assigned this to a variable and then use that as array like bellow.
$userdata=$this->session->userdata('logged_in');
now variable $userdata contain all array field that you set in controller and hence you can use it as $userdata['id'], $userdata['name'] etc
public function __construct()
{
parent::__construct();
$data['session_data']=$this->session->user_data('logged_in');
}
public function some_function(){
$data['dummy']="";
$this->load->view('someview3',$data)
}
public function some_function1(){
$data['dummy']="";
$this->load->view('someview1',$data)
}
public function some_function2(){
$data['dummy']="";
$this->load->view('someview2',$data)
}
If you assign that into the constructor then it will call by automatically whenever a function calls in the controller.
you can view it in you view page by,
print_r($session_data);

Why redirect show blank page in model laravel?

I'd like to ask why the following code works, redirects normally, and data is successfully inserted :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
if($category->saveCategory($data)){
return Redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return Redirect::route('admin_posts_categories')->withError('Failed to add category. #ErrorCode : 13');
}
}
Term model :
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return true;
}else{
return false;
}
}else{
return "#Error Code : 4";
}
}
Where as the following only inserts the data but then shows a blank page and doesn't redirect :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
$category->saveCategory($data);
}
Term Model
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return redirect::route('admin_posts_categories')->withError('Failed to add category.');
}
}else{
return redirect::route('admin_posts_categories')->withError('#Error Code : 4.');
}
}
Moreover, I'd like to ask a few related questions, does my code conform to correct design patterns, and where should I put the redirect, in the model or in the controller ?
Try this for redirect:
1. return Redirect::back()->withSuccess('Category successfully added.');
OR
2. return Redirect::to(URL::to('admin_posts_categories'))->withSuccess('Category successfully added.');
Add your redirect login inside Controller. Even if you want to put in model (which is not recommended) use Ardent Hook function i.e. afterSave().
First of all never put redirect logic in model. Models are for putting business logic. Second thing check whether you have created route for admin_posts_categories in route.php or not and how you are calling views. If possible post your route code in question.
I recommend not putting redirects in your model. So the first solution would be the best of the two you have.
But back to your problem. It is showing a blank page because your store function is not returning anything. return $category->saveCategory($data); but as previously stated this method is not best practise.
An excellent tip would be to have a look at Laracasts, this will teach you everything you knew, didn't know and more about Laravel.

CodeIgniter - Load View after Update

After I have updated a customer (which works fine)
public function update($customer_acc) {
if($this->session->userdata('logged_in'))
{
$id= $this->input->post('did');
$data = array(
'customer_name' => $this->input->post('dname')
);
$this->load->model('update_model');
$this->update_model->update_customer($id,$data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
How can i then load back the view customer function. What i need is after the update has been completed so then go back to viewing the customer.
public function view($customer_acc) {
if($this->session->userdata('logged_in'))
{
$this->load->model('display_single_customer');
$customers = $this->display_single_customer->view_single_customer($customer_acc);
$data['customer_acc'] = $customers['customer_acc'];
$data['customer_name'] = $customers['customer_name'];
$this->load->view('customers_single_view', $data);
}
else
{
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
you just exit to another method in your controller to show the new page. for passing the id you can either pass it directly
if ( some condition ) {
$id = $this->input->post('did', TRUE);
// blah blah blah
// success -- now go to show customer method
$this->showCustomer($id) ; }
function showCustomer($id){
// get the customer to display using the $id that was passed
$customers = $this->display_single_customer->view_single_customer($id);
OR you can declare the id with $this-> and then it is available to any method in the controller
$this->id = $this->input->post('did', TRUE);
// blah blah
$this->showCustomer() ; }
function showCustomer(){
// get the customer to display using $this->id
$customers = $this->display_single_customer->view_single_customer($this->id);
// etc etc
I think i may have sussed it I can use a redirect using the $id which is the customer account number
redirect("/customers/view/$id");
Is this the correct way, It works but is it best practice ?

Codeigniter and Set Session in Model

I want to unset and set session in model function depend on passed id.
I have language field for every record and should change session considering that.
in sample word i have a link like this : http://www.mysite.com/report/2020
now this article by this id maybe saved by english language but current session is french.so I should change the session.
here is my code but it dos not work.
//function for checking language by id
public function lang($id)
{
$data = $this->db
->select('language')
->from('content')
->where('id',$id)
->get();
if ($data->num_rows > 0) {
return $data;
}else{
return false;
}
}
//function for reading data from db depend on id and language
public function report($id)
{
$cat=2;
$code=$id;
$langu= $this->lang($id)->row()->language;
if($langu==3){
$this->session->unset_userdata('lang');
$this->session->set_userdata('lang','dr');
}
if($langu==2){
$this->session->unset_userdata('lang');
$this->session->set_userdata('lang','pa');
}
if($langu==1){
$this->session->unset_userdata('lang');
$this->session->set_userdata('lang','en');
}
$language= $this->session->userdata('lang');
$lang=$language;
$data = $this->db
->select('*')
->from('content')
->where('category',$cat)
->where('language',$lang)
->where('id',$code)
->get();
if ($data->num_rows > 0) {
return $data;
}else{
return false;
}
}
the best way to session is:
you have to check the query in model, and call the model in controller, if its true set session data within controller....
Setting Session within the model is not a good idea for an MVC architecture.
Sometimes there is really need to set or get session data in model.
Use then Code Igniter instance like below:
$codeIgniter =& get_instance();
$codeIgniter->set_userdata('data', $data);
// or to read data:
$data = $codeIgniter->userdata('data');
Note that using $this to call set_userdata() or userdata() in model will not work correctly.

codeigniter: using uri segment in model

I am using uri segment to delete info in my database:
anchor('site/delete_note/'.$row->id, 'Delete')
Model:
function delete_note()
{
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
}
It works fine, but I want to do the same for updating my info and can't get it work
So this is link in view:
anchor('site/edit_note/'.$row->id, 'Edit')
My controller:
function edit_note()
{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}
My model:
function edit_note($note_id)
{
$content = $this->input->post('content');
$data = array('content' => $content);
$this->db->where('id', $note_id);
$this->db->update('note', $data);
}
My view of edit_note:
<?php
echo form_open('site/edit_note');
echo form_textarea('content', set_value('content', 'Your message'));
echo form_submit('submit', 'Change');
echo anchor('site/members_area', 'Cancel');
echo validation_errors('<p class="error">'); ?>
Edit doesn't work as delete, when i am trying to get segment directly in edit model, as I used in delete model.
If I set $note_id to a number in my controller, instead of this '$this->uri->segment(3)', it updates my database. But if I use getting segment it doesn't work. I thought uri segments are available in controller as in model, but there is something I don't know.
Better yet, instead of manually reading the IDs via the segments, you could change your functions to be:
function delete_note($note_id)
and
function edit_note($note_id)
And remove the $note_id = $this->uri->segment(3); lines.
And as silly as it'll sound, the generated URL is definitely correct, right?
And last question, have you done anything with routes?
Edit
I've also noticed that in edit, you use this in your form:
echo form_open('site/edit_note');
So when the form submits, the URL it submits to is site/edit_note instead of site/edit_note/{SOME_ID}. So once you make your changes, and the form submits, there won't be a 3rd URL segment!
Well there are some logical errors in your code.
function edit_note()
{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
//// What is the use of loadig a view when you are editing
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}
Instead do it like this
function edit_note()
{
if($this->input->post()){
$this->load->library('form_validation');
$this->form_validation->set_rules('content', 'Message', 'trim|required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('Note_model');
$this->Note_model->edit_note($note_id);
redirect('site/members_area');
}
}else{
$note_id = $this->uri->segment(3);
$data['main_content'] = 'edit_note';
$this->load->view('includes/template', $data);
}
}
MOST IMPORTANT
And the other thing you should note that you are using anchor to access edit note but not actually submitting a form so it is not getting any post data to update.
In my view it's a 'bad' approach to use uri segments in your models... you should pass an id as a parameter from your controller functions ..
function delete_note()
{
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
}
What if you want to re-use this delete method? e.g. deleting notes from an admin panel, via a cron job etc then the above relies upon the uri segment and you will need to create additional delete methods to do the job. Also, if you were to continue with the same you don't even need a model then .. just call these lines in your controllers if you know what I mean ...
$this->db->where('id', $this->uri->segment(3));
$this->db->delete('note');
so best is to change it to similar to your edit_note() model function.

Resources