Am a new user to CodeIgniter, have looked at other posts and the answers given sadly don't solve this issue.
Am using a form to create records (also uploads image file and creates link to image as field in db) This all works. I am now trying to edit a particular record. I have a view with the form and this works and is pre-filled from the db using $id = $this->uri->segment(3) to grab the correct record - this all works.
Where it fails is then in updating the record.
My controller...
function edit_stock_vehicle_record()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('make', 'Make', 'trim|required');
$this->form_validation->set_rules('model', 'Model', 'trim|required');
$this->form_validation->set_rules('fuel', 'Fuel Type', 'trim|required');
$this->form_validation->set_rules('enginesize', 'Engine Size', 'trim|required');
$this->form_validation->set_rules('trans', 'Transmission', 'trim|required');
$this->form_validation->set_rules('reg_no', 'Registration Number', 'trim|required');
$this->form_validation->set_rules('year', 'Year', 'trim|required');
$this->form_validation->set_rules('colour', 'Colour', 'trim|required');
$this->form_validation->set_rules('mileage', 'Mileage', 'trim|required');
$this->form_validation->set_rules('long_desc', 'Description', 'trim|required');
$this->form_validation->set_rules('purchase_price', 'Purchase Price', 'trim|required');
$this->form_validation->set_rules('sale_price', 'Sale Price', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$data['main_content'] = 'vehicle_display2';
$this->load->view('includes/template', $data);
}
else
{
$this->load->model('manage_model');
if($query = $this->manage_model->edit_stock_vehicle_record())
{
$data['main_content'] = 'vehicle_added';
$this->load->view('includes/template', $data);
}
else
{
$data['main_content'] = 'add_vehicle4';
$this->load->view('includes/template', $data);
}
}
}
My model....
function edit_stock_vehicle_record()
{
$this->load->helper('array');
$this->load->helper('html');
$id = $this->uri->segment(3);
$config['upload_path'] = 'c:/wamp/www/honest/images';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$data['main_content'] = 'imageupload';
$this->load->view('includes/template', $data);
echo "FAILED";
}
else
{
$image_data = $this->upload->data();
$vehicle_update_data = array(
'title' => $this->input->post('title'),
'make' => $this->input->post('make'),
'model' => $this->input->post('model'),
'fuel' => $this->input->post('fuel'),
'enginesize' => $this->input->post('enginesize'),
'trans' => $this->input->post('trans'),
'reg_no' => $this->input->post('reg_no'),
'year' => $this->input->post('year'),
'colour' => $this->input->post('colour'),
'mileage' => $this->input->post('mileage'),
'long_desc' => $this->input->post('long_desc'),
'purchase_price' => $this->input->post('purchase_price'),
'sale_price' => $this->input->post('sale_price'),
'image' => $image_data['file_name']
);
$this->load->helper('url');
$id = $this->uri->segment(3);
$update = $this->db->update('stock_vehicles', $vehicle_update_data, array('id' => $id));
return $update;
}
}
I have also tried versions using....
$this->db->where('id', $id);
$this->db->update('stock_vehicles', $vehicle_update_data);
But this also fails, it seems as if the $id is not being recognized correctly.
If I remove the above and just use $this->db->update('stock_vehicles', $vehicle_update_data); it does indeed update every record in the db (doh!) Fortunately there was no 'real' data in there when I discovered this!
Not sure why it is not picking up the $id - all input gratefully received.
Cheers,
DP.
I have a view with the form and this works and is pre-filled from the
db using $id = $this->uri->segment(3) to grab the correct record -
this all works.
Do NOT do this for the form update. Just include the id in a hidden form field. Much easier, safer, etc.
echo form_hidden( 'id', $id );
first you must load the url helper in your Controller:
$this->load->helper('url');
then you should try this code:
$id = $this->uri->segment(3);
$vehicle_update_data =array(
'title' => $this->input->post('title'),
'make' => $this->input->post('make'),
'model' => $this->input->post('model'),
'fuel' => $this->input->post('fuel'),
'enginesize' => $this->input->post('enginesize'),
'trans' => $this->input->post('trans'),
'reg_no' => $this->input->post('reg_no'),
'year' => $this->input->post('year'),
'colour' => $this->input->post('colour'),
'mileage' => $this->input->post('mileage'),
'long_desc' => $this->input->post('long_desc'),
'purchase_price' => $this->input->post('purchase_price'),
'sale_price' => $this->input->post('sale_price'),
'image' => $image_data['file_name']
);
$this->db->WHERE('id',$id)->update('your_table',$vehicle_update_data);
return true;
Related
I am having a problem with inserting file_path to database and file upload in folder using Codeigniter, I have a form field where user can upload any jpg|png|gif file. But how will I get the file_path of that particular file uploaded and insert it into database and file are stored in floder.
my controller code
public function enqry(){
$data = array();
$postData = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10240;
$this->load->library('upload', $config);
//if add request is submitted
if ( ! $this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageUploadForm', $error);
}else {
print_r('Image Uploaded Successfully.');
}
if($this->input->post('postSubmit')){
//form field validation rules
$this->form_validation->set_rules('name', 'post name', 'required');
$this->form_validation->set_rules('email', 'post email', 'required');
$this->form_validation->set_rules('mobile', 'post number', 'required');
$this->form_validation->set_rules('nationality', 'post nationality', 'required');
$this->form_validation->set_rules('location','post location','required');
//prepare post data
$postData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'nationality' => $this->input->post('nationality'),
'location'=>$this->input->post('location'),
'statuse' => '0',
'created_at' => date("Y-m-d H:i:s")
/*'passport_details'=>$this->input->post('passport_details')*/
);
//validate submitted form data
if($this->form_validation->run() == true){
//insert post data
$insert2 = $this->user_mod->insert_enq($postData);
if($insert2){
$this->session->set_userdata('success_msg', 'Post has been added successfully.');
redirect('/User_con/log/');
}else{
$data['error_msg'] = 'Some problems occurred, please try again.';
}
}
}
$data['post'] = $postData;
$data['title'] = 'Create Post';
}
//load the add page view
public function log_enq(){
$this->load->view('templates/header');
$this->load->view('enquiry_reg');
$this->load->view('templates/footer');
}
My view code
<div class="form-group">
<label for="title">File Upload</label>
<input type="file" name="upload" placeholder="upload">
</div>
My model code
public function insert_enq($data = array()) {
$insert2 = $this->db->insert('tbl_enquiry', $data);
if($insert2){
return $this->db->insert_id();
}else{
return false;
}
}
if (!$this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageUploadForm', $error);
}
else {
$data = $this->upload->data('file_name');
$image = 'your_path'.$data;
}
and add $image variable to your your query like
$arrayName = array(
'imapge' => $image,
'more_column' => $more_column_values);
public function enqry(){
$data = array();
$postData = array();
$postData['upload_path'] = './uploads/';
$postData['allowed_types'] = 'gif|jpg|png';
$postData['max_size'] = 10240;
$this->load->library('upload', $postData);
if (!$this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('user_con/error', $error);
}
else {
$data = $this->upload->data('file_name');
$image = 'your_path'.$data;
}
if($this->input->post('postSubmit')){
$this->form_validation->set_rules('name', 'post name', 'required');
$this->form_validation->set_rules('email', 'post email', 'required');
$this->form_validation->set_rules('mobile', 'post number', 'required');
$this->form_validation->set_rules('nationality', 'post nationality', 'required');
$this->form_validation->set_rules('location','post location','required');
$postData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'nationality' => $this->input->post('nationality'),
'location'=>$this->input->post('location'),
'statuse' => '0',
'created_at' => date("Y-m-d H:i:s"),
'upload' => $image
);
if($this->form_validation->run() == true){
$insert2 = $this->user_mod->insert_enq($postData);
if($insert2){
$this->session->set_userdata('success_msg', 'Post has been added successfully.');
redirect('/User_con/log/');
}else{
$data['error_msg'] = 'Some problems occurred, please try again.';
}
}
}
$data['post'] = $postData;
$data['title'] = 'Create Post';
}
$config = array(
'upload_path' =>'./uploads/',
'allowed_types' =>'jpg|jpeg|png|gif',
'max_size' => '5000KB');
$this->load->library('upload',$config);
$this->upload->initialize($config);
Replace this code your code....and cheack......
I do not understand why upon load the validation always returns false. Here is part of my controller:
// load up the validation rules for blog Info form
$this->config->load('mh_blog_validate');
$this->form_validation->set_rules($this->config->item('validate_blog_update'));
if ($this->form_validation->run('validate_blog_update') === FALSE) {
$errors = array('message' => $this->upload->display_errors());
$message = array('message' => 'Warning - '.$errors['message'],
'class' => 'danger',
);
$this->data['alert'] = bootstrap_alert($message);
}
Here is my validation config from mh_blog_validate:
$config['validate_blog_update'] = array(
'title' => array(
'field' => 'title',
'label' => '',
'rules' => 'required|trim|xss_clean|min_length[5]|callback_is_slug_unique_on_update[]',
'errors' => array(
'required' => 'The title cannot be blank.',
'min_length' => 'The title must be 5 charaters or more.',
'is_unique' => 'The title must be unique.',
'is_slug_unique_on_update' => 'The new title needs to be unique'
),
),
'body' => array(
'field' => 'body',
'label' => '',
'rules' => 'required|trim|xss_clean|min_length[5]',
'errors' => array(
'required' => 'The body cannot be blank',
'min_length' => 'The body must be 5 charaters or more.',
)
),
); // end validate_blog_create
This is the callback function I use in the validate:
function is_slug_unique_on_update() {
$new_slug = url_title($this->input->post('title'));
if ( $new_slug == $this->input->post('slug')) {
// no change in slug so update
// echo "no change in title";
return TRUE;
} elseif ( $new_slug !== $this->input->post('slug')) {
// new slug
$result = $this->Blog_model->is_slug_unique_on_update($new_slug);
return $result; // returns FALSE if the title is not unique
}
}
The output I receive in the view is "Warning - " and this is placed in the view:
if (isset($this->data['alert']){
echo $this->data['alert'];
}
I was expecting the validation not to produce an error because I have not submitted the form. It runs the validation maybe(?) even when I have not submitted the form I think.
+++ new edit +++
Added code below that works and wish to know why mine code doesn't. I thought my code follows the same pattern, no?
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
}
The problem is you are setting $this->data['alert'] values, whether the form is submitting data or not. Of course you could prevent this variable assignment by adding conditional so it will set only when there are any $_POST data is submitted :
// load up the validation rules for blog Info form
$this->config->load('mh_blog_validate');
$this->form_validation->set_rules($this->config->item('validate_blog_update'));
if ($this->form_validation->run('validate_blog_update') === FALSE) {
if ($_POST)
{
$errors = array('message' => $this->upload->display_errors());
$message = array('message' => 'Warning - '.$errors['message'],
'class' => 'danger',
);
$this->data['alert'] = bootstrap_alert($message);
}
}
Please help! I was using codeigniter 3 mvc and my code worked just fine. Then I moved to hmvc and my uploads no longer function. Below is my code:
class Home extends MY_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('User_m', 'user');
$this->load->library('upload');
}
public function register()
{
$data['services'] = $this->user->get_service_list();
$data['page_class'] = 'register-page';
$data['title'] = 'Registration';
$data['content_view'] = 'Home/register_v';
$this->template->login_template($data);
}
public function apply()
{
$directoryname = $this->input->post('company').'/documents';
if (!is_dir('customer_documents/'.$directoryname))
{
mkdir('./customer_documents/' . $this->input->post('name_of_org').'/documents', 0777, TRUE);
}
//Field Rules
$this->form_validation->set_rules('company', 'Company/', 'trim|required|min_length[6]');
$this->form_validation->set_rules('address', 'Physical Address', 'trim|required');
$this->form_validation->set_rules('tel', 'Tel', 'trim|required');
$this->form_validation->set_rules('postal_address', 'Postal Address', 'trim|required');
$this->form_validation->set_rules('contact_name', 'Contact Name', 'trim|required|min_length[6]');
$this->form_validation->set_rules('contact_number', 'Contact Number', 'trim|required|min_length[6]');
$this->form_validation->set_rules('position', 'Position', 'trim|required|min_length[6]');
$this->form_validation->set_rules( 'email', 'Email', 'trim|required|valid_email|min_length[7]');
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++)
{
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config = [
'upload_path' => './customer_documents/'.$directoryname,
'allowed_types' => 'gif|jpg|png|pdf',
'max_size' => '1000000',
'overwrite' => FALSE,
'remove_spaces' => TRUE,
'encrypt_name' => FALSE
];
$this->upload->initialize($config);
$this->upload->do_upload();
$file_data = $this->upload->data();
$name_array[] = $file_data['file_name'];
}
if($this->form_validation->run() == FALSE && !$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$data['services'] = $this->customer->get_service_list();
//Load Template
$data['page_class'] = 'register-page';
$data['title'] = 'Registration';
$data['content_view'] = 'Home/register_v';
$this->template->login_template($data);
}
else
{
$names= implode(',', $name_array);
$data = array(
'name_of_org' => $this->input->post('name_of_org'),
'address' => $this->input->post('address'),
'tel' => $this->input->post('tel'),
'postal_address' => $this->input->post('postal_address'),
'contact_name' => $this->input->post('contact_name'),
'contact_number' => $this->input->post('contact_number'),
'role' => 'admin',
'position' => $this->input->post('position'),
'email' => $this->input->post('email'),
'userfile' => $names,
'service' => $this->input->post('service_id'),
);
//Insert User
$this->user->register($data);
//isset Message
$this->session->set_flashdata('success', 'You have successfully submitted your registration.');
//Redirect
redirect('Home/register');
}
}
Model:
class User_m extends CI_MODEL{
function __construct()
{
parent::__construct();
$this->table = 'users';
}
function register($data)
{
$this->db->insert($this->table, $data);
}
}
When I use the above code to upload files using mvc it works perfectly well but when I transfered it to hmvc it just post other form fields to the database without files yet also creating directory without uploading any files. What might be the problem? Anyone with a solution for this I am stuck. Please help!
Try with absolute path
(!is_dir(FCPATH.'customer_documents/'.$directoryname))
and fix that in all places accordingly.
Also CI_MODEL should be CI_Model
I have a form which accepts some text input fields and a file field (used to upload image).
My problem is like that, if I did not fill one of the required fields and I have selected a valid image file, I will get an error message about the missing field, but the image will be uploaded. The Controller is:
defined('BASEPATH') OR exit('No direct script access allowed');
class Manage extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$config = array(
array(
'field' => 'item_name',
'label' => 'Item name',
'rules' => 'required'
),
array(
'field' => 'item_code',
'label' => 'Item code',
'rules' => 'required|is_unique[_items.item_code]'
),
array(
'field' => 'item_description',
'label' => 'Item description',
'rules' => 'required'
),
array(
'field' => 'item_img',
'label' => 'Item image',
'rules' => 'callback_upload_image'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('is_unique', 'Item code (' . $this->input->post('item_code') . ') already exists.');
if($this->form_validation->run() == FALSE)
{
// Render the entry form again
}
else
{
// Go to another page
}
}
public function upload_image()
{
$config['upload_path'] = './items_images';
$config['max_size'] = 1024 * 10;
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(isset($_FILES['item_img']) && !empty($_FILES['item_img']['name']))
{
if($this->upload->do_upload('item_img'))
{
$upload_data = $this->upload->data();
$_POST['item_img'] = $upload_data['file_name'];
return TRUE;
}
else
{
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
return FALSE;
}
}
else
{
$_POST['item_img'] = NULL;
return FALSE;
}
}
}
As I know, if one rule failed, other fields and operations will be canceled and the form will be loaded again, or other operations will be done.
Thank you,,,
you need to upload the image when validation is true only. so remove your public function upload_image() and write the functionalists inside validation true statement as given below.
defined('BASEPATH') OR exit('No direct script access allowed');
class Manage extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$config = array(
array(
'field' => 'item_name',
'label' => 'Item name',
'rules' => 'required'
),
array(
'field' => 'item_code',
'label' => 'Item code',
'rules' => 'required|is_unique[_items.item_code]'
),
array(
'field' => 'item_description',
'label' => 'Item description',
'rules' => 'required'
),
array(
'field' => 'item_img',
'label' => 'Item image',
'rules' => 'callback_upload_image'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('is_unique', 'Item code (' . $this->input->post('item_code') . ') already exists.');
if($this->form_validation->run() == FALSE)
{
// Render the entry form again
}
else
{
$config['upload_path'] = './items_images';
$config['max_size'] = 1024 * 10;
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(isset($_FILES['item_img']) && !empty($_FILES['item_img']['name']))
{
if($this->upload->do_upload('item_img'))
{
$upload_data = $this->upload->data();
$_POST['item_img'] = $upload_data['file_name'];
return TRUE;
}
else
{
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
return FALSE;
}
}
else
{
$_POST['item_img'] = NULL;
return FALSE;
}
}
// Go to another page
}
}
I found this very helpful post here. The author wrote his own rules to validate the file chosen by user to upload. Code sample:
$this->form_validation->set_rules('file', '', 'callback_file_check');
public function file_check($str){
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return false;
}
}
I have a form that requires the user to enter some information. If they fail to complete the required fields they are re-presented with the form; the top of the page notifying them what fields are required and I've enabled sticky forms (set_value()) so their input is not lost.
I'm using flashdata to display messages to the user (i.e., if what they've entered already exists in the database).
My form is in the index method of my controller.
When submit is clicked from my view it calls the add() method in my controller.
The add() method performs the validation and depending on the results either submits to the database or kicks back out to the user to get more data.
I have several issues with the way that i've done this.
1. If validation fails I'm using $this->index() to get back to my form and display the validation errors. If I try using redirect, I lose my validation errors and my $_POST[] data so my sticky forms end up blank.
2. Using $this->index() appends the 'add' to the end of my url
3. Using $this->index() causes issues with the flashdata. Random results.
Any ideas?
<?php
class Restaurant extends Controller {
function Restaurant() {
parent::Controller();
}
function index() {
// Load libraries and models
$this->load->model('/restaurant/mRestaurantTypes');
$this->load->model('/restaurant/mRestaurant');
$this->load->model('/utilities/mUtilities');
// Get states
$stateSelect = array();
$getStates = $this->mUtilities->getStates();
if($getStates->num_rows() > 0) {
foreach($getStates->result() as $row) {
$stateSelect[$row->abbr] = $row->name;
}
}
// Get restaurant types
$restaurantTypes = array();
$getRestaurantTypes = $this->mRestaurantTypes->getRestaurantTypes();
if($getRestaurantTypes->num_rows() > 0) {
foreach($getRestaurantTypes->result() as $row) {
$restaurantTypes[$row->restaurant_types_id] = $row->type;
}
}
// Create form elements
$data['name'] = array(
'name' => 'name',
'id' => 'name',
'value' => set_value('name'),
'maxlength' => '200',
'size' => '50'
);
$data['address'] = array(
'name' => 'address',
'id' => 'address',
'value' => set_value('address'),
'maxlength' => '200',
'size' => '50'
);
$data['city'] = array(
'name' => 'city',
'id' => 'city',
'value' => set_value('city'),
'maxlength' => '50',
'size' => '25'
);
$data['state'] = $stateSelect;
$data['zip'] = array(
'name' => 'zip',
'id' => 'zip',
'value' => set_value('zip'),
'maxlength' => '10',
'size' => '10'
);
$data['phone'] = array(
'name' => 'phone',
'id' => 'phone',
'value' => set_value('phone'),
'maxlength' => '15',
'size' => '15'
);
$data['url'] = array(
'name' => 'url',
'id' => 'url',
'value' => set_value('url'),
'maxlength' => '255',
'size' => '50'
);
$data['type'] = $restaurantTypes;
$data['tags'] = array(
'name' => 'tags',
'id' => 'tags',
'value' => set_value('tags'),
'maxlength' => '255',
'size' => '50'
);
$data['active'] = array(
'name' => 'active',
'id' => 'active',
'value' => 'Y',
'maxlength' => '1',
'size' => '2'
);
// Set page variables
$data_h['title'] = "Add new restaurant";
// Load views
$this->load->view('/template/header', $data_h);
$this->load->view('/restaurant/index', $data);
$this->load->view('/template/footer');
}
/**
* Add the the new restaurant to the database.
*/
function add() {
// Load libraries and models
$this->load->library('form_validation');
$this->load->model('/restaurant/mRestaurant');
// Define validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[255]|xss_clean');
$this->form_validation->set_rules('address', 'Address', 'trim|required|max_length[100]|xss_clean');
$this->form_validation->set_rules('city', 'City', 'trim|required|max_length[128]|xss_clean');
//$this->form_validation->set_rules('state', 'State', 'trim|required');
$this->form_validation->set_rules('zip', 'Zip', 'trim|required|max_length[128]|xss_clean');
$this->form_validation->set_rules('phone', 'Phone', 'trim|required|max_length[10]|xss_clean');
$this->form_validation->set_rules('url', 'URL', 'trim|required|max_length[255]|xss_clean');
$this->form_validation->set_rules('tags', 'Tags', 'trim|xss_clean');
// Form validation
if ($this->form_validation->run() == FALSE) {
// On failure
$this->index();
} else {
// On success, prepare the data
$data = array(
'name' => $_POST['name'],
'address' => $_POST['address'],
'city' => $_POST['city'],
'state' => $_POST['state'],
'zip' => $_POST['zip'],
'phone' => $_POST['phone'],
'url' => $_POST['url'],
'type' => $_POST['type'],
'tags' => $_POST['tags'],
'active' => $_POST['active'],
);
// Check if the restaurant already exists
$check = $this->mRestaurant->getRestaurant($data['name'], $data['zip']);
// If no records were returned add the new restaurant
if($check->num_rows() == 0) {
$query = $this->mRestaurant->addRestaurant($data);
if ($query) {
// On success
$this->session->set_flashdata('status', '<div class="success">Added New Restaurant!</div>');
} else {
// On failure
$this->session->set_flashdata('status', '<div class="error">Could not add a new restaurant.</div>');
}
redirect('restaurant/confirm', 'refresh');
} else {
// Notify the user that the restaurant already exists in the database
$this->session->set_flashdata('status', '<div class="notice">This restaurant already exists in the database.</div>');
redirect('restaurant/index');
}
}
}
function confirm() {
$data['title'] = "Confirm";
$this->load->view('/template/header');
$this->load->view('/restaurant/confirm', $data);
$this->load->view('/template/footer');
}
}
?>
I will try to help with the logic in the controller that I always use:
function index()
{
//set some default variables
$data['error_message'] = '';
//if this is to edit existing value, load it here
// from database and assign to $data
//...
//set form validation rules
$validation = array();
$validation['field_name'] = array(
'field' => 'field_name',
'label' => 'Field label',
'rules' => 'trim|required'
);
//more rules here
//...
$this->load->library('form_validation');
$this->form_validation->set_rules($validation);
//run validation
if ($this->form_validation->run() == FALSE)
{
$data['error_message'] .= validation_errors();
}
else
{
//do insert/update
//
//it's better to do redirection after receiving post request
//you can use flashdata for success message
if ( $success )
{
$this->session_set_flashdata('success_message', MESSAGE_HERE);
}
redirect(RESULT_PAGE);
}
//reaching this block can have 2 meaning, direct page access, or not have valid form validation
//assign required variables, such as form dropdown option, etc
//...
//load view
$this->load->view(VIEW_FILE, $data);
}
View file:
...
<?php if ( $error_message ): ?>
<?php echo $error_message; ?>
<?php endif; ?>
<?php echo form_open(current_url, array('id' => 'some_form_id')); ?>
<!-- form field here -->
<label for="field_name">Field label</label>
<input name="field_name" value="<?php echo set_value('field_name', $DEFAULT_FIELD_NAME_IF_NEEDED); ?>" />
<!-- more form field here -->
<?php echo form_close(); ?>
...
I hope this will help you.
For the $DEFAULT_FIELD_NAME_IF_NEEDED in the view file, I use this to pass the default value if this form page is to edit existing data from database. You can load the data in the controller, then pass it to view file and display it in the form field.
-------controller-------
$data['post'] = $_POST;
$this->load->view('view/view', $data);
then in your view
<input type="text" value="><?=$post['username'];?>" name="username">
I had a similar problem and I ended up doing:
My form is to create new user but you should get the idea.
if($this->form_validation->run() == FALSE)
{
$this->data['title'] = "Add User";
$this->load->vars($this->data);
$this->load->view('head');
$this->load->view('header');
$this->load->view('admin/sidebar');
$this->load->view('admin/add_user');
$this->load->view('footer');
}
So effectively instead of calling new function I was showing new view from the same function.
Not the nicest solution but it works.
Also you might want to use something like this to check if the restaurant already exists:
function _check_username($str)
{
$this->db->where('username', $str);
$query = $this->db->get('sm_users');
if($query->num_rows() == 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('_check_username', "User '$str' already exists!");
return FALSE;
}
}
And use callback validation function:
$this->form_validation->set_rules('userName','User Name','trim|required|min_length[3]|callback__check_username');
You could try having the form post to index, and in the index method, do validation if the form has been submitted. Then either render the index view (if there are errors) or add the restaurant and render the confirm view.