I'm currently developing a system in CodeIgniter that requires user authentication via login & registration as a base in order to use the rest of the system. I've been having a 404 Not Found issue on my system whenever I try to call a Controller function, this is particularly prevalent on form submissions. I've posted my related code from my Controller, Model, View, Routes and Htaccess below. I'm not entirely sure whats causing the 404 not found error, any help would be greatly appreciated.
Controller:
// handles register page
public function register() {
$this->load->helper('form');
$this->load->library('form_validation');
$data['title'] = "Register";
$this->form_validation->set_rules('fullname','Full Name','required');
$this->form_validation->set_rules('accountid','Account ID','required');
$this->form_validation->set_rules('password','Password','required');
$this->form_validation->set_rules('type','Account Type','required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('register', $data);
} else {
$fullname = $this->input->post('fullname');
$username = $this->input->post('username');
$password = md5($this->input->post('password'));
$accounttype = $this->input->post('type');
$this->system->registeruser($username, $password, $fullname, $accounttype);
echo "User Registration Complete";
}
}
Model:
public function registeruser($accountid, $password, $fullname, $accounttype) {
$query = "INSERT INTO users VALUES($fullname','$accountid','$password','$accounttype')";
$this->db->query($query);
}
View:
<?php
echo form_open('main/register');
echo validation_errors(); ?>
<div id="name-input">
<?php
$data = array(
'name' => 'fullname',
'value' => $this->input->post('fullname'),
'placeholder' => 'Full Name',
'class' => '',
'style' => 'width:100%; padding:0.5em;' );
echo form_input($data);
echo "</p>"; ?>
</div>
<div id="username-input">
<?php
$data = array(
'name' => 'accountid',
'value' => $this->input->post('accountid'),
'placeholder' => 'User ID',
'class' => 'username',
'style' => 'width:100%; padding:0.5em;' );
echo form_input($data);
echo "</p>"; ?>
</div>
<div id="password-input">
<?php
$data = array(
'name' => 'password',
'value' => $this->input->post('password'),
'placeholder' => 'Password',
'class' => 'passwordd',
'style' => 'width:100%; padding:0.5em;' );
echo form_password($data);
echo "</p>"; ?>
</div>
<div id="account-type">
<?php
$options = array(
'student' => 'Student',
'lecturer' => 'Lecturer' );
$data = array(
'name' => 'type',
'style' => 'width:100%; padding:0.5em;' );
echo form_dropdown($data, $options);
echo "</p>"; ?>
</div>
<div id="submit-button">
<?php
$data = array(
'name' => 'register',
'value' => 'Register Account',
'class' => 'register',
'style' => 'width:100%; padding:0.5em;' );
echo form_submit($data); ?>
</div>
<?php echo form_close(); ?>
Routes:
$route['main/register'] = 'main/register';
$route['default_controller'] = 'main';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
Htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
All the code above relates to my registration page / it's related functions, I have multiple of these errors on my system currently but they all seem to be the same thing, I figured solving one may solve the rest as well.
I don't know the exact cause of your problem, but following solution should work.
Remove
echo form_open('main/register');
line and add
echo "<form action='' method='post' >";
(leave the action attribute empty, so it will submit data to the current page)
Remove
$route['main/register'] = 'main/register';
line.
Extra suggestion: Don't use md5(), because it is not secure. Use password_hash() instead.
Try removing the route $route['main/register'] = 'main/register';. Also, give method POST to the form. And input field names do not match in controller as well as model.
Edit:
Form action should be a complete URL-
echo form_open(base_url()."/controllername/mehod"); In your case it should be echo form_open(base_url()."/main/register");
If you haven't set base_url then
Step 1: Open the config.php file under application\config folder
step 2: Set the value of $config['base_url'] to your website path
$config['base_url'] = "http://localhost/foldername/index.php";
That should help. :)
Related
I'm working on a comment section for my blog post in CodeIgniter, I based myself on a tutorial by Brad Traversy and I followed each step carefully but somehow it does not work within my template.
This is show method in my Post Controller:
public function show($slug)
{
// Get Posts by Slug
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Get Comments per Post
$post_id = $data['posts']['id']; // Here is where I get the error
$data['comments'] = $this->Post_model->get_comments($post_id);
// If empty show a 404 error
if(empty($data['posts'])){
show_404();
}
// Load template
$this->template->load('public', 'default', 'posts/show', $data);
}
I created a variable $post_id in order to get the comments for the current post that is being visited by an user. All this should come from my Post_model:
public function get_comments($post_id){
$this->db->select('username,email,website,body');
$this->db->from('comments');
$query = $this->db->get_where('comments', array('post_id' => $post_id));
return $query->result_array();
}
This is where I'm creating the form to add the comment:
<!-- Form -->
<h4>Add a comment</h4>
<?php echo validation_errors('<p class="alert alert-danger">'); ?>
<?php echo form_open('public/comments/add_post_comment/'.$post['id']); ?>
<!-- Username -->
<div class="form-group">
<?php echo form_label('Username', 'username'); ?>
<?php
$data = array(
'id' => 'username',
'name' => 'username',
'class' => 'form-control',
'placeholder' => 'John Doe',
'value' => set_value('username')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Email -->
<div class="form-group">
<?php echo form_label('E-mail', 'email'); ?>
<?php
$data = array(
'id' => 'email',
'name' => 'email',
'class' => 'form-control',
'placeholder' => 'JohnDoe#demo.com',
'value' => set_value('email')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Website -->
<div class="form-group">
<?php echo form_label('Website', 'website'); ?>
<?php
$data = array(
'id' => 'website',
'name' => 'website',
'class' => 'form-control',
'placeholder' => 'https://www.example.com',
'value' => set_value('website')
);
?>
<?php echo form_input($data) ?>
</div>
<!-- Comments Body -->
<div class="form-group">
<?php echo form_label('Body', 'body'); ?>
<?php
$data = array(
'id' => 'body',
'name' => 'body',
'class' => 'form-control',
'placeholder' => 'Write here',
'value' => set_value('body')
);
?>
<?php echo form_textarea($data); ?>
</div>
<!-- Hidden Input -->
<?php
$data = array(
'name' => 'slug',
'value' => $posts->slug,
);
?>
<?php echo form_hidden($data); ?>
<!-- Submit Button -->
<?php echo form_submit('mysubmit', 'Add Comment', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
<?php endif; ?>
This is the Controller I'm using to add comments to the specific $post_id:
public function add_post_comment($post_id)
{
// Field Rules
$this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[3]');
$this->form_validation->set_rules('body', 'Body', 'trim|required|min_length[3]');
if ($this->form_validation->run() == FALSE) {
// Set Message
$this->session->set_flashdata('error', 'There was an error in proccessing the comment. Please, try again.');
// Redirect to current page
redirect(site_url() . 'posts/show/'.$post_id);
} else {
// Get Post by Slug
$slug = $this->input->post('slug');
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Create Post Array
$data = array(
'post_id' => $post_id,
'username' => $this->input->post('username'),
'user_id' => $this->session->userdata('user_id'),
'email' => $this->input->post('email'),
'website' => $this->input->post('website'),
'body' => $this->input->post('body'),
);
// Insert Comments
$this->Comments_model->add($data);
// Set Message
$this->session->set_flashdata('success', 'Your comment has been posted');
// Redirect to same page if form was not successful or submitted
redirect(site_url() . 'posts/show/'.$post_id);
}
}
All this should work according to some tutorials that I have seen before but this time is not.
The error comes from my function show. Any idea on how to fix this?
Thanks for helping.
Ok well as you would have read in the codeigniter users guide - $query->row() will return an object.
So you would use $data['posts']->id. Which may or may not work with your current PHP Version. I'm open to be corrected on that point.
If you want an associative array, as you are attempting to use, then you would use $query->row_array();
If you had performed a var_dump like...
public function show($slug)
{
// Get Posts by Slug
$data['posts'] = $this->Post_model->get_by_slug($slug);
// Quick Debug to Eyeball what is actually being returned.
var_dump($data['posts']);
exit();
// Get Comments per Post
$post_id = $data['posts']['id']; // Here is where I get the error
$data['comments'] = $this->Post_model->get_comments($post_id);
// If empty show a 404 error
if(empty($data['posts'])){
show_404();
}
// Load template
$this->template->load('public', 'default', 'posts/show', $data);
}
You would see ( and its always a good check when validating your code ) what is being returned by $this->Post_model->get_by_slug($slug);
It's a very good idea to know how to "look" at what your variables are and check they are what you think they should be.
I am getting this error in CakePHP from my forgot_password method which is in UsersController.
public function forgot_password() {
$this->layout = 'signin';
if (!empty($this->data)) {
$user = $this->User->findByUsername($this->data['User']['username']);
if (empty($user)) {
$this->Session->setflash('Sorry, the username entered was not found.');
$this->redirect('/users/forgot_password');
}else{
$user = $this->__generatePasswordToken($user);
if ($this->User->save($user) && $this->__sendForgotPasswordEmail($user['User']['id'])) {
$this->Session->setflash('Password reset instructions have been sent to your email address.
You have 24 hours to complete the request.');
$this->redirect('/users/login');
}
}
}
}
Here is the forgot_password.ctp file
<header class="panel-heading text-center">
<strong>Forget Password</strong>
</header>
<h3>Enter Your Username</h3>
<?php
echo $this->Form->create('User', array('action' => 'forgot_password', 'id' => 'web-form', 'class'=>'panel-body wrapper-lg'));
echo $this->Form->input('username', array('label' => 'Username', 'between'=>'<br />', 'type'=>'text', 'div' => 'form-group','class' => 'form-control input-lg'));
?>
<div class="form-group">
<?php echo $this->Form->submit('Send Password Reset Instructions', array('class' => 'btn btn-primary btn-techuz', 'id' => 'submit')); ?>
</div>
<?php echo $this->Form->end(); ?>
It's not necessary to specify the form action if it's same as the view. In case you'd like to redirect to a different action, try this:
<?php
echo $this->Form->create('User', array(
'url' => array(
'controller' => 'users','action' => 'forgot_password'
),
'id' => 'web-form',
'class' =>'panel-body wrapper-lg'
)
); ?>
If you follow the convention and define this "url" index as an array of controller and index, you're bound to be safe and deprived of errors.
Peace! xD
Got the solution, no need to mention 'action' => 'forgot_password' in forgot_password.ctp file until it is redirect to another method.
Here is my validation rule in User.php
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'User name is required'
),
'alphaNumeric'=>array(
'rule' => 'alphaNumeric',
'required' => true,
'message' => 'Alphabets and numbers only'
)
))
and this is my view page code
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username'));
echo $this->Form->input('email', array('label' => 'Email'));
echo $this->Form->input('password', array('label' => 'Password'));
echo $this->Form->submit('Sign Up');
echo $this->Form->end();
?>
Here is my controller code
public function register() {
$this->layout = 'starter';
//debug($this->validationErrors);
if ($this->request->is('post')) {
if ($this->User->validates()) {
$this->User->save($this->request->data);
$this->Session->setFlash(__('Please login your account'));
$this->redirect('/users/login');
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
but validation message is not showing. What is wrong in my code?...
Your code is wrong.
if ($this->request->is('post')) {
if ($this->User->validates()) {
$this->User->save($this->request->data);
this is not how it could ever work as the data is not passed prior to validation.
You need to first pass the data, then validate, then optionally save (or save and validate together):
if ($this->request->is('post')) {
if ($this->User->save($this->request->data)) {}
or, careful not to retrigger validation twice:
if ($this->request->is('post')) {
$this->User->set($this->request->data);
if ($this->User->validates()) {
$success = $this->User->save(null, array('validate' => false));
But that is documented.
The latter only makes sense if you really need to do this in two steps.
In your comment you have written you have changed layout page.It may you miss
<?php echo $this->Session->flash(); ?>
this line.Add this line in your view/layouts/yourlayout.ctp file.
Disable HTML5 required in your view page code
<?php
echo $this->Form->create('User');
echo $this->Form->input('username', array('label' => 'Username','required'=>'false'));
echo $this->Form->input('email', array('label' => 'Email','required'=>'false'));
echo $this->Form->input('password', array('label' => 'Password','required'=>'false'));
echo $this->Form->submit('Sign Up');
echo $this->Form->end();
?>
I am using Ionauth library in codeigniter and edited edit_user() method in Auth controller to enable individual user updating his/her own user settings. So when a logged in user goes to : siteurl/auth/edit_user it shows the user settings just fine. But when I hit the save button I got an error: "This form post did not pass our security checks". Though the default url (siteurl/auth/edit_user/userID) works fine, For individual non-admin user I want to keep the url without userID at the end.
here is my edit_user() method:
//edit a user
function edit_user($id=NULL)
{
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || (!$this->ion_auth->is_admin() && !($this->ion_auth->user()->row()->id == $id) && !($id==NULL )))
//if (!$this->ionauth->logged_in() || !$this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
if($id==NULL){
$user = $this->ion_auth->user()->row();
}else{
$user = $this->ion_auth->user($id)->row();
}
$groups=$this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
/**if (isset($user->phone) && !empty($user->phone))
{
$user->phone = explode('-', $user->phone);
} **/
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
if(!($this->input->post('email')==$user->email)){
$this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'required|valid_email|is_unique[users.email]');
}else{
$this->form_validation->set_rules('email', $this->lang->line('edit_user_validation_email_label'), 'required|valid_email');
}
/** $this->form_validation->set_rules('phone2', $this->lang->line('edit_user_validation_phone2_label'), 'required|xss_clean|min_length[3]|max_length[3]');
$this->form_validation->set_rules('phone3', $this->lang->line('edit_user_validation_phone3_label'), 'required|xss_clean|min_length[4]|max_length[4]');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean'); **/
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
//$this->form_validation->set_message('is_unique[users.email]','Email already exists or Invalid');
if (isset($_POST) && !empty($_POST))
{
// do we have a valid request?
if ($this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id'))
{
show_error($this->lang->line('error_csrf'));
}
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email' => $this->input->post('email'),
/** 'phone' => $this->input->post('phone1') . '-' . $this->input->post('phone2') . '-' . $this->input->post('phone3'), **/
);
//if($this->ion_auth->is_admin()){
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
}
}
//}
//update the password if it was posted
if ($this->input->post('password'))
{
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
}
if ($this->form_validation->run() === TRUE)
{
$this->ion_auth->update($user->id, $data);
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth", 'refresh');
}
}
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
//if($this->ion_auth->is_admin()){
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
//}
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name),
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name),
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'text',
'value' => $this->form_validation->set_value('email', $user->email),
);
/** $this->data['phone1'] = array(
'name' => 'phone1',
'id' => 'phone1',
'type' => 'text',
'value' => $this->form_validation->set_value('phone1', $user->phone[0]),
);
$this->data['phone2'] = array(
'name' => 'phone2',
'id' => 'phone2',
'type' => 'text',
'value' => $this->form_validation->set_value('phone2', $user->phone[1]),
);
$this->data['phone3'] = array(
'name' => 'phone3',
'id' => 'phone3',
'type' => 'text',
'value' => $this->form_validation->set_value('phone3', $user->phone[2]),
); **/
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->load->view('header');
$this->_render_page('auth/edit_user', $this->data);
$this->load->view('footer');
}
and this is my view file (edit_user.php):
<h1><?php echo lang('edit_user_heading');?></h1>
<div id="body">
<p><?php echo lang('edit_user_subheading');?></p>
<div id="infoMessage"><?php echo $message;?></div>
<?php echo form_open(uri_string());?>
<p>
<?php echo lang('edit_user_fname_label', 'first_name');?> <br />
<?php echo form_input($first_name);?>
</p>
<p>
<?php echo lang('edit_user_lname_label', 'last_name');?> <br />
<?php echo form_input($last_name);?>
</p>
<p>
<?php echo lang('edit_user_email_label', 'email');?> <br />
<?php echo form_input($email);?>
</p>
<!--
<p>
<?php echo lang('edit_user_phone_label', 'phone');?> <br />
<?php echo form_input($phone1);?>-<?php echo form_input($phone2);?>-<?php echo form_input($phone3);?>
</p>
-->
<p>
<?php echo lang('edit_user_password_label', 'password');?> <br />
<?php echo form_input($password);?>
</p>
<p>
<?php echo lang('edit_user_password_confirm_label', 'password_confirm');?><br />
<?php echo form_input($password_confirm);?>
</p>
<?php //if($this->ion_auth->is_admin()){ ?>
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php foreach ($groups as $group):?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php endforeach?>
<?php //} ?>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<p><?php echo form_submit('submit', lang('edit_user_submit_btn'));?></p>
<?php echo form_close();?>
The csrf check is failing.
Try taking out $id = NULL in the method declaration (you don't need it anyway if you're sending the id via POST). Or explicitly set $id = $this->input->post('id'); before doing the csrf check.
In my case I was using relative URLs for the images and css files used in the site. Using base_url() to all the URLs present in the site fixed the problem. No issue now.
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.