i want to access unit_id from get_material() method which return data from the modal product_modal.. The function codes..
public function get_material() {
$query = $this->db->get('tbl_receivings_items');
return $query->result();
}
The second function which I want to use unit_id from the above function is
public function get_material_item_unit($p_unit_id){
$sql = "SELECT * FROM tbl_unit WHERE unit_id = ?";
$q = $this->db->query($sql, $p_unit_id);
if($q->num_rows() >0){
return $q->result();
}else{
return null;
}
}
I access both functions from the controller known as manufacture **, in which both functions have been called inside **add_product() function as follows
public function add_product(){
$formRules = array(
array(
'field' => 'prod_name',
'label' => 'Product Name',
'rules' => 'trim|required',
),array(
'field' => 'partner',
'label' => '',
'rules' => 'trim',
),array(
'field' => 'prod_qty',
'label' => 'Quantity To Produce',
'rules' => 'trim|required|greater_than_equal_to[1]',
)
);
$this->form_validation->set_rules($formRules);
if($this->form_validation->run() == TRUE){
$can_be_consumed_value = $this->input->post('can_be_consumed');
$can_be_solded_value = $this->input->post('can_be_sold');
if($can_be_consumed_value == false){
$can_be_consumed_value ="0";
}else{
$can_be_consumed_value ="1";
}
if($can_be_solded_value == false){
$can_be_solded_value ="0";
}else{
$can_be_solded_value ="1";
}
$data =array(
'prod_name' => $this->input->post('prod_name'),
'can_be_consumed' => $can_be_consumed_value,
'can_be_sold' => $can_be_solded_value,
'prod_partner' => $this->input->post('partner'),
'created_by' => $this->input->post('created_by'),
'date_created' => date('Y-m-d'),
'prod_desc' => $this->input->post('prod_desc'),
'prod_qty' =>$this->input->post('prod_qty')
);
$query = $this->product_model->add_product($data);
if($query){
$data['initial_data'] = $this->product_model->get_product_data($query);
$data['material_list'] = $this->product_model->get_material();
$m_list = $this->product_model->get_material();
if($m_list->num_rows() > 0)
{
foreach($m_list->result() as $m){
$data['unit_list'] = $this->product_model->get_material_item_unit($m->unit_id);
}
}
$this->session->set_flashdata('success_msg', 'Product Created Successfully');
$this->load->view('manufacture/manufacture_step_2', $data,'refresh');
}else{
$this->session->set_flashdata('error_msg', 'Sorry! Fail to create product');
redirect('manufacture');
}
}else{
echo '<div class="alert alert-danger error">'.validation_errors().'</div>';
}
}
The add_product() function works properly means that it send data to db.
My Problem: every time I try to access the unit_id through a while loop I get an error of Undefined property: stdClass::$unit_id. i will appreciate your help.
the while loop
$data['initial_data'] = $this->product_model->get_product_data($query);
$data['material_list'] = $this->product_model->get_material();
$m_list = $this->product_model->get_material();
if($m_list->num_rows() > 0)
{
foreach($m_list->result() as $m){
$data['unit_list'] = $this->product_model->get_material_item_unit($m->unit_id);
}
}
I don't know what is the SQL extension that you are using in PHP but normally when you get the results of a query these results are an array of values.
You are trying to get the data like an object and this is the reason that PHP shows you this error because the var $m is not an object.
You can try to do a var_dump($m) and you can see what is the type and the structure of the variable. If $m is an array you must use $m['columnName'] to get the value.
Related
I want to check if record is exist then fire error message else insert into database using codeigniter
model.php
public function insert_profile($data){
$this->db->insert('profile', $data);
}
controller.php
public function empprofile(){
$this->form_validation->set_rules('txtname', 'Name', 'trim|required|min_length[6]',
array(
'required' => 'enter your name'));
$this->form_validation->set_rules('txtemail', 'Email', 'trim|required|valid_email',
array(
'required' => 'enter email'));
$this->form_validation->set_rules('txtvpno', 'Vastipatrak No', 'trim|required|min_length[11]',
array(
'required' => 'select Vastipatrak No'));
$this->form_validation->set_rules('txtfield', 'Field', 'trim|required',
array(
'required' => 'enter Field'));
$this->form_validation->set_rules('txtcontact', 'Phone No', 'trim|required|min_length[10]|max_length[10]',
array(
'required' => 'select Phone No'));
$this->form_validation->set_rules('txtexp', 'Experience', 'trim|required',
array(
'required' => 'enter Experience'));
$this->form_validation->set_rules('txtage', 'Age', 'trim|required',
array(
'required' => 'enter age'));
if($this->form_validation->run() ==FALSE){
$this->load->view('submitprofile');
}
else{
$data = array(
'Name' => $this->input->post('txtname'),
'Email' => $this->input->post('txtemail'),
'VPNo' => $this->input->post('txtvpno'),
'Field' => $this->input->post('txtfield'),
'Phone' => $this->input->post('txtcontact'),
'Exp' => $this->input->post('txtexp'),
'Age' => $this->input->post('txtage')
);
$result= $this->mymodel->insert_profile($data);
if ($result == FALSE) {
echo "Vastipatrak No already exist";
}
elseif ($result == 0) {
echo "Something Went Wrong";
}
else{
echo "You have successfully registred with KDOJobs";
}
redirect(site_url('talents'));
}
}
What i can do to check if record is exists or not if yes then display error
In Model
public function insert_profile($data)
{
$VPNo = $data['VPNo'];
$query = $this-db->query("SELECT * FROM profile WHERE vpno = '$VPNo' ");
$result = $query->result_array();
if (count($result) > 0)
{
# data exist
return FALSE;
}
else
{
$this->db->insert('profile', $data);
if ($this->db->affected_rows() > 0)
{
return TRUE;
}
else
{
return 0;
}
}
}
In Controller
$result = $this->mymodel->insert_profile($data);
if ($result == FALSE) {
$this->session->set_flashdata('error', 'Data exist');
}
elseif ($result == 0) {
$this->session->set_flashdata('error', 'Something Went Wrong');
}
else{
$this->session->set_flashdata('success', 'Successfullly Inserted');
}
/*
In your code you using redirect(). So its better to add session like Flash Data.
So once you redirect as soon as function success you can access it in redirected page.
Setting Flash Data
If error
$this->session->set_flashdata('error', 'Data exist');
$this->session->set_flashdata('error', 'Something Went Wrong');
If Success
$this->session->set_flashdata('success', 'Successfullly Inserted');
Accessing Flash data
if(!empty($this->session->flashdata('error'))
{
echo $this->session->flashdata('error');
}
*/
redirect(site_url('talents'));
Links
Flashdata in Codeigniter
There's a better way to use is_unique[table.coloum_name] , I think, still using CodeIgniters' validation library... Use is_unique where you pass an extra parameter which is the id of the row you're editing.. See below.. I use it and works pretty fine for me.. is_unique[table.coloum_name] hope it helps
$this->form_validation->set_rules('txtname', 'Name', 'trim|required|min_length[6]|is_unique[table.coloum_name]', array( 'required' => 'enter your name'));
https://www.codeigniter.com/userguide3/libraries/form_validation.html
So i have two radio button named Result that have value Fit and Unfit. And one form input that named Detail. If the Unfit is checked then the Detail must be filled. How do i set the validation. currently i have callback function in the controller like this:
public function _is_detail_required()
{
$result = $this->input->post('Result', true);
if ($result != 'Unfit') {
$detail = $this->input->post('Detail', true);
if ($result == 'Unfit') {
$this->form_validation->set_message('_is_detail_required', '%s harus diisi.');
return false;
}
}
return true;
}
and this is the validation rules (on models directory) that i set for the Detail:
$form_rules = array(
array(
'field' => 'Result',
'label' => 'Result',
'rules' => 'trim|xss_clean|required|max_length[50]'
),
array(
'field' => 'Detail',
'label' => 'Detail',
'rules' => 'trim|xss_clean|callback__is_detail_required|max_length[50]'
)
);
my problem is, this callback function is not working. how do i fix this? Any help will be very much appreciated.
You can try to add this in your form validation:
$CI =& get_instance();
if ($CI->input->post('Result') == 'Unfit') {
$form_rules[] = array(
'field' => 'Detail',
'label' => 'Detail',
'rules' => 'trim|xss_clean|required|max_length[50]'
);
}
Note: If your validation is located in your controller, use $this. If not, use $CI =& get_instance(); instead.
The callback function that I wrote is wrong, it didnt check if the input form (Detail) is empty, so this is the correct one
public function _is_detail_required()
{
$result = $this->input->post('Result', true);
if (! empty($result) && $result == 'Unfit') {
$detail = $this->input->post('Detail', true);
if (empty($detail)) {
$this->form_validation->set_message('_is_detail_required', '%s harus diisi.');
return false;
}
}
return true;
}
I am trying to insert an element into my 'category' table and use the inserted element's id to insert another element into my 'subcategory' table.
This is my code in my controller
public function insertCategory(){
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category_id = $this->admin_model->insertCategory($category);
$this->admin_model->insertSubcategory($category_id, $subcategory);
}
}
And this is my code in my model
function insertCategory($category){
$data = array(
'category' => $category,
'status' => 1
);
$this->db->insert('category', $data);
$this->db->select('id');
$this->db->from('category');
$this->db->where('category', $category);
$this->db->limit(1);
$query = $this->db->get();
return $query->result();
}
function insertSubcategory($category_id, $subcategory){
$data = array(
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
);
$this->db->insert('subcategory', $data);
}
However I am getting this error
I already tried using $category_id = (array) $this->admin_model->insertCategory($category); but it still doesn't work
How do I overcome this error? Thank you for the help.
$this->admin_model->insertSubcategory($category_id, $subcategory);
$category_id is an array , so , you must do it like this:
$this->admin_model->insertSubcategory($category_id[0]->field, $subcategory);
You should try this
$this->admin_model->insertSubcategory($category_id[0]->id;, $subcategory);
try this code
Model
public function insert($table, $data)
{
if($this->db->insert($table,array $data))
{
return $this->db->insert_id();
}else
return false
}
controller
public function insertCategory(){
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('subcategory', 'Subcategory', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('ADMIN_ADDCategory');
}
else{
$category = $this->input->post('category');
$subcategory = $this->input->post('subcategory');
//data must be an array
$data = [
'category' => $category,
'status' => '1'
];
$category_id = $this->admin_model->insert('tablename',$data)
if($category_id != false)
{
$data = [
'category_id' => $category_id,
'subcategory' => $subcategory,
'status' => 1
];
if($this->admin_model->insert('table name', $data) != false)
{
echo 'success';
//or load your success page
}else{
echo 'failed';
//or load your success page
}
}else{
echo 'failed';
//or load your success page
}
}
}
I can't seem to get my form validation working with Codeigniter. I've tried extending the Form_validation class by creating My_Form_validation.php and have had no success. I'm now trying the callback method. I was getting errors to show up for a little while, however they were incorrect.
This is the code that is located in my controller:
function create_user() {
$this->load->library('form_validation');
$validate = array(
array(
'field' => 'first_name',
'label' => 'First Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'last_name',
'label' => 'Last Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|xss_clean|callback_user_exists'
),
array(
'field' => 'email_address',
'label' => 'Email Address',
'rules' => 'trim|required|valid_email|callback_email_exists'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[5]|max_length[32]'
),
array(
'field' => 'password2',
'label' => 'Confirm Password',
'rules' => 'trim|required|matches[password]'
)
);
$this->form_validation->set_rules($validate);
if($this->form_validation->run() == FALSE) {
$this->load->view('user/user-signup');
} else {
$this->load->model('user_model');
if($query = $this->user_model->create_user()) {
$this->load->view('user/user-login');
} else {
$this->index();
}
}
}
function user_exists($username) {
$this->load->model('user_model');
$this->user_model->user_exists($username);
$this->form_validation->set_message('user_exists', 'This username is already taken');
}
function email_exists($email) {
$this->load->model('user_model');
$this->user_model->email_exists($email);
$this->form_validation->set_message('email_exists', 'This email is already in use');
}
And this is the code located in my Model:
function create_user() {
$insert_user = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'username' => $this->input->post('username'),
'email_address' => $this->input->post('email_address'),
'password' => md5($this->input->post('password'))
);
$insert = $this->db->insert('users', $insert_user);
return $insert;
}
function user_exists($username) {
$this->db->where('username', $username);
$query = $this->db->get('users');
if($query->num_rows > 0) {
return true;
} else {
return false;
}
}
function email_exists($email) {
$this->db->where('email_address', $email);
$query = $this->db->get('users');
if($query->num_rows > 0) {
return true;
} else {
return false;
}
}
I'm wanting to validate by checking to see if a Username or Email Address already exists in the database, and if so, the user will need to make the appropriate changes.
Any ideas?
Your code is very hard to read, so I'll show you how improve it. :)
In your controller, you can use constructor for model loading instead this two lines:
$this->load->model('user_model');
Like this:
function __constructor() {
parent::__constructor();
$this->load->model('user_model');
}
Change your user_exists callback to this:
function user_exists($username) {
$user_check = $this->user_model->user_exists($username);
if($user_check > 0) {
$this->form_validation->set_message('user_exists', 'This username is already taken');
return FALSE;
}
else {
return TRUE;
}
}
Change your email_exists callback to this:
function email_exists($email) {
$check_email = $this->user_model->email_exists($email);
if($check_email > 0) {
$this->form_validation->set_message('email_exists', 'This email is already in use');
return FALSE;
}
else {
return TRUE;
}
}
Now, go back to your model and change these two models methods:
function user_exists($username) {
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->num_rows();
}
function email_exists($email) {
$this->db->where('email_address', $email);
$query = $this->db->get('users');
return $query->num_rows();
}
Now, you do it wrong because you don't understand what model means. in the models methods, you can write database queries... So, if you want to create an user, you should get inputs' information in the controller and then pass them to the model method create_user, like this:
Controller method create_user:
function create_user() {
$this->load->library('form_validation');
$validate = array(
array(
'field' => 'first_name',
'label' => 'First Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'last_name',
'label' => 'Last Name',
'rules' => 'trim|required|xss_clean'
),
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|xss_clean|callback_user_exists'
),
array(
'field' => 'email_address',
'label' => 'Email Address',
'rules' => 'trim|required|valid_email|callback_email_exists'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[5]|max_length[32]'
),
array(
'field' => 'password2',
'label' => 'Confirm Password',
'rules' => 'trim|required|matches[password]'
)
);
$this->form_validation->set_rules($validate);
if($this->form_validation->run() == FALSE) {
$this->load->view('user/user-signup');
} else {
$user_data['first_name'] = $this->input->post("first_name");
$user_data['last_name'] = $this->input->post("last_name");
$user_data['username'] = $this->input->post("username");
$user_data['email_address'] = $this->input->post("email_address");
$user_data['password'] = $this->input->post("password");
if($query = $this->user_model->create_user($user_data)) {
$this->load->view('user/user-login');
} else {
$this->index();
}
}
}
Model's method create_user:
function create_user($user_data) {
return $this->db->insert("users", $user_data);
}
That's all, it will work. Good luck.
Have you tried is_unique[table_name.field_name] rule?
Example:
$this->form_validation->set_rules('username', 'Username',
'required|min_length[5]|max_length[12]|is_unique[users.username]');
$this->form_validation->set_rules('email', 'Email',
'required|valid_email|is_unique[users.email]');
Update
If you want to use a callback function then user_exists function should be in the controller instead in the model as you mentioned.
The correct way to define is -
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
Re-write your function like this
function user_exists($username) {
$this->load->model('user_model');
$result = $this->user_model->user_exists($username);
if($result != NULL){
$this->form_validation->set_message('user_exists', 'This username is already taken');
return FALSE;
}else{
return TRUE;
}
}
You are not returning true or false therefore it is always getting last true returned by xss_clea.
i have had the same problem.
One of the problems with the callback function is that it can only accept one parameter.
there are two states to consider when checking for uniqueness of a record in your form.
1) you are adding a new record
2) you are editing an existing record.
if you are adding a new record the inbuilt is_unique works fine.
if you are editing an existing record is_unique does not work, because it finds the record you are editing and says the form data is not unique.
to get around this problem i have used the session class, set it for case 2 before you run the validation script, so you need to know if you are editing an existing record, or adding a new record. to do this i just add a hidden input to the form when it is edited, eg the records unique id.
presumably you have a unique user id in your users table, eg so set it before the validation is run.
if($this->input->post('user_id')){$this->session->set_userdata('callback_user_id',$this->input->post('user_id'));}
then in your callback, use this sort of algorithm:
case 1) ie $this->session->userdata('callback_user_id') == FALSE
if the user name is unique, validate, and return true.
if the user name is not unique, return false with validation message user has to be unique.
case 2) ie, the callback_user_id is set.
if the user name is unique, validate and return true
if the user name is already set, and that record has the same id as user_id, that means you are updating the same record, and its fine to validate.
otherwise, another record has the username, and it should fail validation.
in the model i just have a method that returns the unique id for a username.
after you run the validation, its probably a good idea to unset the callback_user_id session variable.
i'm sorry i don't have code to paste, but i think this description should help you.
==== edits
nowadays, i think overriding the form validation with a new function is the way to go.
so: have a language pack entry, a form validation line and the override:
This assumes that a field is posted named ID that has the id of the row.
$lang['form_validation_is_unique_not_current'] ='The {field} field must contain a unique value.';
array('field' => 'username', 'label' => 'lang:…username…', 'rules' => 'trim|required|min_length[2]|max_length[40]|is_unique_not_current[users.username]'),
class MY_Form_validation extends CI_Form_validation {
function __construct($rules = array())
{
parent::__construct($rules);
$this->_error_prefix = '<div class="alert alert-danger"><p>';
$this->_error_suffix = '</p></div>';
}
public function is_unique_not_current($str, $field)
{
sscanf($field, '%[^.].%[^.]', $table, $field);
$id = $this->CI->input->post('id');
if($this->CI->input->post('field_name'))
{
return isset($this->CI->db)
? ($this->CI->db->limit(1)->get_where($table, array(
$field => $str,
'id <> ' => $id))->num_rows() === 0)
: FALSE;
}
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.