Unable to access controller data in codeigniter views - php

I use the following code in my controller. But the data['msg'] is not being passed to the view file.
Code:
class Operator{
public function view ($page)
{
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = $this->getTitle($page);
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
public function create_company()
{
// some code
$data['msg1']='my mesg';
redirect('operator/view/operator_success','refresh');
}
};
When operator_success(view page) is loaded it show error message: variable '$msg1' not defined.

It's because data['msg1'] is set, then the page is redirected (not carrying the data array with it).
If you want data to persist, then you need to either use sessions or cookies.

After Redirect you cannot use the variable or array. Instead setting the variable keep in session or CodeIgniter Flash Data.
class Operator
{
public function view($page)
{
if (!file_exists('application/views/pages/' . $page . '.php')) {
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = $this->getTitle($page);
$this->load->view('templates/header', $data);
$this->load->view('pages/' . $page, $data);
$this->load->view('templates/footer', $data);
}
public function create_company()
{
// some code
$data['msg1'] = 'my mesg';
// DO THIS
$this->session->set_flashdata('msg1', 'my mesg');
// OR
$this->session->set_userdata('msg1', 'my mesg');
redirect('operator/view/operator_success', 'refresh');
}
}
After redirect you can simply call the flashdata.
echo $this->session->flashdata('msg1');
// OR
echo $this->session->userdata('msg1');
You must initialize the session before use, either autoload the session library or load manually.
[ 1 ] Autoload the session library (config/autoload.php)
$autoload['libraries'] = array('session');
[ 2 ] Manually load the library
$this->load->library('session');
see more about session and flash data here. Hope this helps you. Thanks!!

you have redirect after setting variable so you must set this message either in session ("flash" message) or on operator/view/operator_success controller

Related

codeigniter - how to prevent F5 from resubmitting a form

I have the following method in my controller:
(shortened version but all the key pieces are here...)
class Widget extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('widget_model');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function assign()
{
//logic to display form.
if ($this->input->method() == "get" ) {
$data['save_status'] = '';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
else
{
//logic to handle POST
...
$data['save_status'] = 'Sucessfully saved to db';
$data['title'] = 'Assign Widget';
$data['main_content'] = "assign";
$this->load->view('includes/template',$data);
}
}
Everything works, except I don't know what the proper way to clear the form data is... because when I press F5 thinking I'm refreshing my page, it's actually resubmitting the data to the database.
Sorry, i'm sure this is a noob question.
Thanks.
EDIT 1
for now, I added a redirect at the end of post logic like this;
redirect(base_url()."index.php/thesamecontroller/thesamemethod");
and that takes the user to the same page, but without the form data being available.
Is this the best way to handle it?

Codeigniter MVC - Loading views without losing controller data and form validation

This doesn't make sense to me with how MVC works in codeigniter.
I have a 'controller/Company.php' loads using example.com/company/
function index() {
$page = uri_string();
$data['title'] = ucfirst($page);
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
}
This loads 'views/company.php' and displays form:
<h1 class="page-title"><?php echo $title; ?></h1>
<?php echo form_open('company/update', 'class="form-horizontal" role="form"'); ?>
<input name="company_name" type="text">
<?php echo form_error('company_name'); ?> //if empty display error
//rest of form and submit button
I then have an update function inside the Company controller:
function update() {
$this->form_validation->set_rules('company_name', 'Company Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('company');
} else {
//update db, load model, post data, success, etc
}
}
My issues are:
If I just load the form view again then I lose my header, nav, footer, etc.
If I redeclare all 4 of those views, I lose the original data variables: $title, $page
If I use redirect('company'); to load the controller again then I would lose the submitted data and the form_error('company_name'); would be empty
I hope I'm missing something big because I have been staring at this all day and search for answers but can't find a tutorial of how all of this is suppose to work in the "real world" Thanks
Yes of course. Controller method act as single function in your project.
if i explain it more
<?php
public function one()
{
echo '1';
}
public function two()
{
echo '2';
}
In here function one don't know what is function two. So both functions are acting as Independent.
According to your question
you load this views in index()
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view($page, $data);
$this->load->view('templates/footer', $data);
but in update() you load only
$this->load->view('company');
so in second function there are no header, navigation, and footer.
Answer for your Question is
<?php
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view('company');
$this->load->view('templates/footer', $data);
} else
{
//update db, load model, post data, success, etc
}
For question Two
you can use like this
<?php
if ($this->form_validation->run() == FALSE)
{
$page = uri_string();
$data['title'] = ucfirst($page);
$this->load->view('templates/header', $data);
$this->load->view('templates/top_nav', $data);
$this->load->view('company');
$this->load->view('templates/footer', $data);
} else
{
//update db, load model, post data, success, etc
}

Code Igniter Validation on Error

I am pretty knew to code igniter / OOP but I am giving it a shot and a little stumped at this point.
I have 2 functions. One is the search which loads data from a model. The other is the save function.
My issue is, when running save() I am getting errors because its trying ti display the validation errors but we no longer have the data from the database that we got from the search() function.
I feel that it would be redundant to include all the details form the search back into this save function which is why I think I am doing something wrong.
public function search()
{
// Define some vars
$data['title'] = 'Submit Attrition';
$data['js_file'] = 'submit.js';
// Load our helper
$this->load->helper('form');
// Get the user and pass it to the model
$empQID = $this->input->post('empQID');
$data['userDetails'] = $this->submit_model->get_details($empQID);
$data['languages'] = $this->submit_model->get_languages();
$data['types'] = $this->submit_model->get_types();
$data['ratings'] = $this->submit_model->get_ratings();
$data['processes'] = $this->submit_model->get_processes();
// Send the data to the views
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
/**
* Validate & save attrition submission
*
* #author Carl
* #return void
*/
public function save()
{
$data['title'] = 'Submit Attrition';
$this->load->library('form_validation');
$this->form_validation->set_rules('language', 'Supporting Language', 'required');
// Validation failed, show form w/ validation errors
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('submit/search', $data);
$this->load->view('templates/footer', $data);
}
else
{
// Success : Send data to model
$this->submit_model->save_attrition();
$this->load->view('templates/header', $data);
$this->load->view('submit/success', $data);
$this->load->view('templates/footer', $data);
}
}
I'm not sure I entirely understand your question, but I think I understand what you're trying to do. In CodeIgniter, you do something like this:
class MyController
{
// this controller action will load whether the form is submitted or not
// $user_id is set by the router
public function save($username)
{
// if the users not in the database, throw a 404 error
$user = $this->db->get_where('users', ['username' => $username]);
if(!$user) {
return show_404();
}
// if it's not a post request, then the form hasn't been submitted
// so don't bother validating it
if($router->fetch_method() === 'POST' && $form_validation->run() === TRUE)
{
$user['name'] = $this->input->post('name');
$this->db->update('users', $user);
$this->load->view('success_page');
// return so we don't render the form again
return;
}
// this will happen in all cases, __except__ when the form was submitted
// with valid data
$this->load->view('form');
}
}
I've skipped on details for brevity (like loading the relevant libraries), and because I can't remember all the CI syntax.

Passing array form controller to other controller

One other question – in the user controller login method, after checking pressed button (login or forget password), in line : $data = $this->user_model->login(); return correct user information; "user name, family, user id" to be used in dashboard for using in log table and heAder of pages how to send this data to dashboard?
i tried to send it via redirect() but it fail
if ($this->form_validation->run() == TRUE) {
if (!empty($_POST['login'])) {
$data = $this->user_model->login();
if ($data != NULL)
{
redirect('dashboard');
} else {
redirect('user/login', 'refresh');
}
} elseif (!empty($_POST['forget'])) {
redirect('user/recover');
}
}
$this->data['subview'] = 'users/login';
$this->load->view('users/_layout_modal', $this->data);
Function redirect() doesn't save anything. You can try save $data to session by writing $this->session->set_userdata('some_name', $data);
Then you can call them with $this->session->userdata('some_name');
Note that $data can be object or array.
Assume that $data is array, then in dashboard you can use something like this:
$data = $this->session->userdata('some_name');
echo 'Username: '.$data['username'].'<br />';
echo 'Family: '.$data['family'];
...... so on ........
As per your question, you are validating the user login details and creating session for them.
Then store user information in session.
set session library auto-load in config/autoload.php. Then create session as below.
$this->session->set_userdata(
array(
"username"=>$username,
"user_id" => $user_id,
"family" => $family
)
);
In Dashboard:
You can access session with it's name:
echo $this->session->userdata("username");

User's name doesn't update in header after login

I am using CodeIgniter + Registration/Login script from HTML Form Guide. I wanted to have user's name displayed in the navbar (logged in as: [username]). So in controllers I've added a variable:
$data['login'] = '';
$this->load->view('templates/header', $data);
$this->load->view('templates/nav', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
and in the nav.php :
<?php
if ($login!='')
echo "Logged in as: ".$login;
?>
In the Access Controlled Page, which is loaded after login:
$login = $fgmembersite->UserFullName();
which is:
function UserFullName()
{
return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
}
User's name is correctly returned in Access Controlled Page, but not in the navbar. I believe it is because of the order that views are loaded. Before templates/nav is loaded, the variable $data['login'] is probably being cleared according to what I declared in controllers. Is there a workaround for this?
Why do you need to add $data['login'] in your controller anyways? If you have your user logged in you must have put that information in your session right? If not just save the name of the logged-in user in the session first.Eg.
$this->session->set_userdata('logged_user_name', $username);
Now, in the pages where you want to show the name just do this:
if( $this->session->userdata('logged_user_name') ){
echo $this->session->userdata('logged_user_name');
}
Use the following order of code segments-
code segment1:
$data['login'] = '';
$this->load->view('templates/header', $data);
$this->load->view('templates/nav', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
code segment2:
function UserFullName()
{
return isset($_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
}
code segment3:
$login = $fgmembersite->UserFullName();
code segment4:
<?php
if ($login!='')
echo "Logged in as: ".$login;
?>

Categories