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

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
}

Related

CodeIgniter Redirection from form input

I've never used a PHP framework, but I wanted to learn how to use one so I could more easily program for my company, so I chose CodeIgniter.
I am following the code igniter tutorial for a news section so I could learn how things work - but I am having some issues/questions.
Now, I am to the point in the tutorial that I have a form that submits and takes me to a success page. In normal PHP this is where I would just redirect the page to the view page of the news item submitted. In CodeIgniter I have a view function in my controller here
public function view($slug = NULL)
{
$data['news_item'] = $this->news_model->get_news($slug);
if (empty($data['news_item']))
{
show_404();
}
$data['title'] = $data['news_item']['title'];
$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}
I'm not sure how to get the slug from the form when it is submitted.
Here is my create function (Basically the one that inserts the database info and redirects to news/success)
public function create()
{
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = 'Create a news item';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('text', 'Text', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('news/create');
$this->load->view('templates/footer');
}
else
{
$this->news_model->set_news();
$this->load->view('news/success');
}
}
But I want this to redirect to the view page. To do that I need to have the slug I believe. So it should redirect to news/view/$slug - but I'm not sure how to do this.
My set_news model:
public function set_news()
{
$this->load->helper('url');
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'text' => $this->input->post('text')
);
return $this->db->insert('news', $data);
}
You should use something like that:
redirect('news/view/'.url_title($this->input->post('title'), 'dash', TRUE));

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.

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;
?>

404 page not found CodeIgniter Login

This is my first time using CodeIgniter and I am trying to create a Log In form. Whenever I click on the submit button that I have created, it brings me to a 404 Page Not Found Error.
I have made a view_login.php in the view folder with this code:
<?php echo form_open('user/login') ?>
<ul>
<li>
<label> username </label>
<div>
<?php echo form_input(array('id' => 'username', 'name' => 'username')); ?>
</div>
</li>
<li>
<label> password </label>
<div>
<?php echo form_password(array('id' => 'password', 'name' => 'password')); ?>
</div>
</li>
<li><?php echo validation_errors(); ?></li>
<li>
<?php echo form_submit(array('name' => 'submit'), 'login'); ?>
</li>
This is my user.php controller:
<?php
class User extends CI_controller
{
public function __construct()
{
parent::__construct();
$this->load->model('user_model');
}
public function register()
{
$this->load->library('form_validation');
if($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('user/view_register');
$this->load->view('templates/footer');
}
else
{
echo 'this is being processed. thank you';
}
$this->load->view('user/view_register');
}
public function login()
{
$this->load->library('form_validation');
$data['title'] = 'Log In';
$this->load->view('user/view_login');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('user/view_login');
$this->load->view('templates/footer');
{
else
{
$user_id = $this->User_model->check_login($this->input->post('username',
$this->input->post('password');
Here is my User_model:
class User_model extends Model {
function User_model()
{
parent::Model();
}
function check_login($username, $password)
{
$sha1_password = sha1($password);
$query_str = "SELECT user_id FROM users WHERE username = ? and password = ?";
$result = $this->db->query($query_str, array($username, $sha1_password));
if ($result->num_rows() ==1)
{
return $result->row(0)->user_id;
}
else
{
return false;
}
Any help would be immensely appreciated :)
I know you're going to delete your question eventually, as you did with your previous three (that I know of), but hey.
You're doing a lot of things wrong. Let's do some cleanup:
<?php
class User extends CI_controller
{
// constructor is useless here, let's remove it.
function index()
{
redirect('login','refresh');
// this is useless too, but just in case someone navigates to the url 'user'
}
function login()
{
// you are calling form_validation methods, and loading the library _after_.
// It's the other way around.
// Also, no need to load the form helper, it's already loaded
// by the form_validation library
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|trim|max_length[200]|xss_clean');
$this->load->view('pages/view_login');
if ($this->form_validation->run() == FALSE) {
$this->load->view('view_login');
{
else {
//extract($_POST);
// this is quite bad practice imho (it's like goring back to register_globals).
// You should fetch the post content directly:
$user_id = $this->user_model->check_login($this->input->post('username',
$this->input->post('password');
}
}
?>
Now, as I said in your previous questions, which all dealt with the SAME EXACT 404 ERROR, I'm going to tell you again: FOLLOW THE MANUAL. Don't invent new ways of using the built-in framework functions. They're there for a purpose.
You should open the form like this:
<?php echo form_open('user/login'); ?>
It will build the correct url by itself. And don't tell "I already did that" again, because you didn't, in fact every question of yours still shows the same mistakes in url building all over again.
I'm sorry to be harsh, I hope something will get grasped eventually.
function user()
{
parent::Controller();
}
should be
function user()
{
parent::__construct();
}
also you are loading
$this->load->view('pages/view_login');
and
$this->load->view('view_login');
check your code, sure these views exists both?
also i really think you can remove all this part:
function index()
{
$this->login();
}
also, you are using index.php in form open, are you removing that from url with htacces? 404 is page not found
This is where your problem could be. I suspect you are confusing your controller name with a subdirectory inside view:
$this->load->view('user/view_login');
Currently, You are loading the view_login.php from a folder/directory known as user. You get a 404 Page Not Found Error if page is not in the referenced directory. It does not exist.
I think this is some error, because user is actually your controller and should be used only from the form as:
<?php echo form_open('user/login'); ?>
except your have view_login.php existing in a subdirectory known as user.
view/
user/
view_login.php
Try putting view_login.php directly into the view folder and use this to call it:
view/
view_login.php
$this->load->view('view_login');
In same vein,
$this->load->view('templates/header', $data);
$this->load->view('user/view_login');
$this->load->view('templates/footer');
Also means that header.php and footer.php are in subdirectories "templates". An error with any of these would give you the 404 error. You might want to try commenting out your load view and test by echoing out some string -- just to prove your codes are all fine.
Verify if you might be having interference from your htaccess file by testing if every other url works well.
[UPDATE]
If you have doubts whether your form action is correct, try using base_url() if that is configured correctly.
<?php echo form_open(base_url().'user/login') ?>
That should accurately point to site/controller/method(function)
Like I mentioned in my comment, I didn't see you use form_validation->rule() anywhere in your code. You could possible check to see if it was false.
Replace your login function with the one below and test:
public function login() {
$this->load->library('form_validation');
$data['title'] = 'Log In';
if ($this->input->post()) {
print_r(); //test if you have values
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
//You could set delimiter
if ($this->form_validation->run() == FALSE) {
//What so ever you which to do if validation fails. { else {
$username = $this->input->post('username'); //Make your code a bit readable
$password = $this->input->post('password'); //Make your code a bit readable
$user_id = $this->User_model->check_login($username, $password);
$data["user_id"] = $user_id; //you can access $user_id from your view
}
}
//Pass $data to views, you might need it in more than one view. Also change directory from user to pages to match what you stated in comment below. And please make sure these views are in the directories specified below...
$this->load->view('templates/header', $data);
$this->load->view('pages/view_login', $data);
$this->load->view('templates/footer', $data);
}

Unable to access controller data in codeigniter views

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

Categories