I am trying to pass multiple parameters to my model from my controller. It seems that the $scholId that I am trying to pass won't go through to the model after I submit the form. However, the $userId goes through to the database just fine. Is there something wrong with $this->uri->segment(4) that won't pass through correctly?
function apply()
{
$this->load->helper('form');
$this->load->library('form_validation');
$scholId = $this->uri->segment(4);
$userId = '2'; //User query -> this will be taken from session
$this->data['scholarship'] = $this->scholarship_model->getScholarship($scholId);
$this->data['title'] = "Apply";
$this->form_validation->set_rules('essay', 'Essay', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $this->data);
$this->load->view('student/page_head', $this->data);
$this->load->view('student/form', $this->data);
$this->load->view('templates/footer', $this->data);
}else{
// Validation passes
$this->users_model->applySchol($userId,$scholId);
redirect('/scholarships');
}
}
you need to check up the segment whether it exists or not before passing it Like:
if ($this->uri->segment(4) === FALSE)
{
$schoId = 0; //or anything else so that you know that does not exists
}
else
{
$schoID= $this->uri->segment(4);
}
or simply:
$product_id = $this->uri->segment(4, 0);
//which will return 0 if it doesn't exists.
Related
Hi i have this form when save, saved into the database. I want that when the data is saved into the database i will get the id on it then displaying it to the next page.
Here's my controller below in my function add_new
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Create_album extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->model('admin_model', 'am');
$this->load->library('form_validation');
if(!$this->session->userdata('logged_in')){
redirect('login');
}
}
public function detail($id){
return $id;
$this->data['item'] = $this->am->getItem($id);
print_r($this->data['item']);exit;
}
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$itemId);
}
}
public function index(){
$this->data['title'] = 'Create Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}
}
my model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Admin_model extends CI_Model{
public function getItem($id){
return $this->db->select('item.id,
item.parent_id,
item.title,
item.description,
item.filename
'
)
->from('item')
->where('item.id', $id)
->get()->result_object();
$this->db->get('item');
}
}
?>
Can someone help me figured this out? i want to get the ID when the data is saved. Any help is muchly appreciated. Thank you
Simply use this
$this->db->insert_id(); // Returns your row id.
Here how your controller should look like
public function add_new(){
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == FALSE){
$this->data['title'] = 'Create New Album';
$this->data['logout'] = 'logout';
$this->data['home'] = 'activities';
$session_data = $this->session->userdata('logged_in');
$this->data['id'] = $session_data['id'];
$this->data['username'] = $session_data['username'];
$this->load->view('pages/admin_header', $this->data);
$this->load->view('content/create_album', $this->data);
$this->load->view('pages/admin_footer');
}else{
$array = array(
'title'=>$this->input->post('title'),
'description'=>$this->input->post('description')
);
$this->am->saveAlbum($array);
$id = $this->db->id;
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
foreach($this->data['item'] as $item){
$itemId = $item->id;
}
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id()); // here?
}
}
Think you're probably looking for the insert_id() query helper function. You can see info about it in the Codeigniter docs.
When PHP hits return in a function it does just that, return a value, and it exits the function. Code following the return will not be executed. Read about it on the docs page
Example:
public function detail($id){
return $id;
echo 'here';
}
You will never get 'here' to echo, since you have already returned a value in your function().
Again this applies twice in your code, once here:
return $itemId;
redirect('create_album/detail/id/'.$this->db->insert_id());
and again here:
$this->data['item'] = $this->am->getItem($id);
return $this->am->saveAlbum($id);
If you want the insert id you are going to have to return it from $this->am->saveAlbum(); Assign that to a variable and pass it to your redirect.
There are quite a few other issues, but that should help to get you started.
I'm new to codeigniter and so when I set up my log in code I started out with simple and kept updating it to be more complex/secure. With that said I was making great progress creating a session and adding a user_data variable called "login_status" set to "1". To use as a reference for future page requests. Eventually I decided to go ahead and set up the database table ci_sessions and switch to that instead of just using a cookie. When I did this, all of the sudden my "login_status" variable was not being written anymore. As a result I could no longer access any subsequent pages and kept being redirected back to the log in screen.
In short, this exact same code works perfectly when I have sess_use_database set to false.
I'm not sure why this is happening but any help would be greatly appreciated!
Log in Controller:
class login extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('form');
}
public function index($login = "")
{
$data = array();
if ($login == "failed")
$data['loginFailed'] = true;
else
$data['loginFailed'] = false;
$this->load->view('templates/headerAdmin');
$this->load->view('admin/loginform', $data);
$this->load->view('templates/footerAdmin');
}
public function assessme()
{
$username = $_POST['username'];
$password = md5($_POST['password']);
//checkme works fine and returns true
if ($this->checkme($username, $password))
{
$newdata = array( 'login_status' => '1' );
$this->session->set_userdata($newdata);
$this->mainpage();
}
else {$this->index("failed");}
}
public function checkme($username = "", $password = "")
{
if ($username != "" && $password != "")
{
$this->load->model('admin/loginmodel');
if ($this->loginmodel->validateCredentials($username, $password))
return true;
else
return false;
}
else
{
return false;
}
}
public function mainpage()
{
redirect('admin/dashboard');
}
The controller that I am redirected to after I can successfully log in:
class dashboard extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index() {
//Make sure user is logged in
$login_status = $this->session->userdata('login_status');
//This is where I am redirected because the user_data is not being set
if(!isset($login_status) || $login_status != '1') {
redirect('admin/login');
}
$this->load->view('templates/headerAdmin');
$this->load->view('admin/dashboard/list');
$this->load->view('templates/footerAdmin');
}
}
Config:
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = TRUE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
EDIT : Setting 'sess_match_useragent' to FALSE seems to prevent the session from being destroyed. Hopefully that will provide other clues as to what the cause of my problem is but obviously this, in itself, isn't an ideal solution
I had this problem and I fix it by this page
http://philsbury.co.uk/blog/code-igniter-sessions
This page say u should change Session library in \system\libraries
I Rename default Session file And create new Session file and put the code on it
its Worked
i am developing an application where i need some suggestions. Here is the detail of the problem.
public function form()
{
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
if($data = $this->input->post()){
$result = $this->form_validation->run();
if($result){
if($id > 0){
// here update code
}else{
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}
}else{
//$this->call_post($data);
$this->session->set_flashdata('message','The Red fields are required');
$this->view = FALSE;
$this->redirect = "mycontroller/form/$id";
}
}else{
$row = $this->mymodel->fetch_row($id);
$this->data[]= $row;
}
}
public function _remap($method, $parameters)
{
if (method_exists($this, $method))
{
$return = call_user_func_array(array($this, $method),$parameters);
}else{
show_404();
}
if(strlen($this->view) > 0)
{
$this->template->build('default',array());
}else{
redirect($this->redirect);
}
}
Here you can see how i am trying to reload the page on failed validation.
Now the problem is that i have to display the flash data on the view form which is only available after redirect and i need to display the validation errors to which are not being displayed on redirect due to the loss of post variable. If i dont use redirect then cant display flashdata but only validation errors. I want both of the functionalities togather. I have tried even creating POSt again like this
public function call_post($data)
{
foreach($data as $key => $row){
$_POST[$key] = $row;
}
}
Which i commented out in the formmethod.How can i achieve this.
Here's a thought.
I think you can add the validation error messages into the flash data. Something like this should work:
$this->session->set_flashdata('validation_error_messages',validation_errors());
Notice the call to the validation_errors function. This is a bit unconventional, but I think it should work. Just make sure that the code are executed after the statement $this->form_validation->run(); to make sure the validation error messages are produced by the Form Validation library.
well i have little different approach hope will help you here it is
mycontroller extend CI_Controller{
function _remap($method,$params){
switch($method){
case 'form':
$this->form($params);
break;
default:
$this->index();
break;
}
}
function form(){
$this->load->helper('inflector');
$id = $this->uri->segment(3,0);
$this->form_validation->set_rules('name','Named','required|trim');
$this->form_validation->set_rules('email','email','required|valid_email|trim');
// if validation fails and also for first time form called
if(!$this->form_validation->run()){
$this->template->build('default',array());
}
else{ // validation passed
$this->save($id)
}
}
function save($id = 0){
$data = $this->input->post();
if($id == 0){
$this->mymodel->insert($data);
$this->session->set_flashdata('message','The page has been added successfully.');
$this->redirect = "mycontroller/index";
$this->view = FALSE;
}else{
// update the field
$this->session->set_flashdata('message','The Red fields are required');
}
redirect("mycontroller/index");
}
}
your form/default view should be like this
<?
if(validation_errors())
echo validation_errors();
elseif($this->session->flashdata('message'))
echo $this->session->flashdata('message');
echo form_open(uri_string());// post data to same url
echo form_input('name',set_value('name'));
echo form_input('email',set_value('email'));
echo form_submit('submit');
echo form_close();
try it if you face any problem post here.
i need to set a input file as required into my Codeigniter Controller.
This is my form_validation:
$this->form_validation->set_rules('copertina','Foto principale','required|xss_clean');
and this is the form:
<?php echo form_open_multipart('admin/canile/nuovo'); ?>
<li class="even">
<label for="copertina">Foto principale <span>*</span></label>
<div class="input"><input type="file" name="copertina" value="<?php echo set_value('copertina'); ?>" id="copertina" /></div>
</li>
<?php echo form_close(); ?>
But after the submit the form say that the file is not set, so the required clausole fails...how can i fix it?
File upload data is not stored in the $_POST array, so cannot be validated using CodeIgniter's form_validation library. File uploads are available to PHP using the $_FILES array.
It maybe possible to directly manipulate the $_POST array using data from the $_FILES array, before running form validation, but I haven't tested this. It's probably best to just check the upload library process for errors.
In addition, it is not possible, for security reasons, to (re-)set the value on page reload.
To make validation to work for files you have to check whether is it empty.
like,
if (empty($_FILES['photo']['name']))
{
$this->form_validation->set_rules('userfile', 'Document', 'required');
}
you can solve it by overriding the Run function of CI_Form_Validation
copy this function in a class which extends CI_Form_Validation .
This function will override the parent class function . Here i added only a extra check which can handle file also
/**
* Run the Validator
*
* This function does all the work.
*
* #access public
* #return bool
*/
function run($group = '') {
// Do we even have any data to process? Mm?
if (count($_POST) == 0) {
return FALSE;
}
// Does the _field_data array containing the validation rules exist?
// If not, we look to see if they were assigned via a config file
if (count($this->_field_data) == 0) {
// No validation rules? We're done...
if (count($this->_config_rules) == 0) {
return FALSE;
}
// Is there a validation rule for the particular URI being accessed?
$uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;
if ($uri != '' AND isset($this->_config_rules[$uri])) {
$this->set_rules($this->_config_rules[$uri]);
} else {
$this->set_rules($this->_config_rules);
}
// We're we able to set the rules correctly?
if (count($this->_field_data) == 0) {
log_message('debug', "Unable to find validation rules");
return FALSE;
}
}
// Load the language file containing error messages
$this->CI->lang->load('form_validation');
// Cycle through the rules for each field, match the
// corresponding $_POST or $_FILES item and test for errors
foreach ($this->_field_data as $field => $row) {
// Fetch the data from the corresponding $_POST or $_FILES array and cache it in the _field_data array.
// Depending on whether the field name is an array or a string will determine where we get it from.
if ($row['is_array'] == TRUE) {
if (isset($_FILES[$field])) {
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_FILES, $row['keys']);
} else {
$this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
}
} else {
if (isset($_POST[$field]) AND $_POST[$field] != "") {
$this->_field_data[$field]['postdata'] = $_POST[$field];
} else if (isset($_FILES[$field]) AND $_FILES[$field] != "") {
$this->_field_data[$field]['postdata'] = $_FILES[$field];
}
}
$this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
}
// Did we end up with any errors?
$total_errors = count($this->_error_array);
if ($total_errors > 0) {
$this->_safe_form_data = TRUE;
}
// Now we need to re-set the POST data with the new, processed data
$this->_reset_post_array();
// No errors, validation passes!
if ($total_errors == 0) {
return TRUE;
}
// Validation fails
return FALSE;
}
Have you looked at this ->
http://codeigniter.com/user_guide/libraries/file_uploading.html
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
Update as per comment:
You can check using plain php if you like ...
$errors_file = array(
0=>'Success!',
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2=>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3=>'The uploaded file was only partially uploaded',
4=>'No file was uploaded',
6=>'Missing a temporary folder',
7=>'Cannot write file to disk'
);
if($_FILES['form_input_file_name']['error'] == 4) {
echo 'No file uploaded';
}
if($_FILES['form_input_file_name']['error'] == 0) {
echo 'File uploaded... no errors';
}
This is sample of function in the Staff controller for this question
function newStaff()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
From the function add_newStaff(), i need to load back all the data from database if the form validation return false. This can be troublesome since I need to maintain two copy of codes. Any tips that I can use to prevent this?
Thanks.
Whats preventing you from doing the following
function newStaff()
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
function add_newStaff()
{
//when user submit the form, it will call this function
//if form validation false
if ($this->validation->run() == FALSE)
{
$data = $this->_getData();
$this->load->view('staff/newstaff', $data);
}
else
{
//submit data into DB
}
}
private function _getData()
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
return $data;
}
Alternately you change the action your form submits to so that it points to the same service you use for the initial form request with something like the following. This would also mean that you'd have the POST values retained between page-loads if you wanted to retain any of the submitted values in your form.
function newStaff()
{
// validation rules
if ($this->validation->run() == TRUE)
{
//submit data into DB
}
else
{
$data = array();
$data['departmentList'] = $this->department_model->list_department();
$data['branchList'] = $this->branch_model->list_branch();
$data['companyList'] = $this->company_model->list_company();
$this->load->view('staff/newstaff', $data);
}
}