how to validate form in a order codeigniter - php

I would like to validate my login form like Google does.
First check username then check password; If both are empty then there is only an error on the username box.
In CodeInginter, if both are empty it prints each field is required messages.
Can we mimic this functionality easily with CodeIgnightor?

you need to research before you post some question. These kind of information available in codeIgniter user guide. Any way i am providing simple example.
View file: login.php
<form action="<?php echo ROOT_FOLDER ?>/controller_name/post_login" method="post" >
<p>
<label>Email:</label> <?php echo form_error('email'); ?><br />
<input type="text" class="text" name="email" value="<?php echo set_value('email'); ?>" />
</p>
<p>
<label>Password:</label> <?php echo form_error('passwd'); ?><br />
<input type="password" name="passwd" class="text" value="" />
</p>
<p>
<input type="submit" class="submit" value="Login" />
</p>
</form>
Controller function which is written in controller file..........
public function post_login()
{
$error_in_validation=set_form_validation($this->config->item('login_form'));
if($error_in_validation){
show_form_validation_error('controller_file_name/login');
}
else
{
$email=$this->input->post('email');
$passwd=$this->input->post('passwd');
$ret=$this->model_file_name->user_login($email, $passwd);
if($ret == NULL){
$model=array();
$model['error_msg']=$this->config->item('login_form_error_code_1');;
$this->load->view('controller_file_name/login',$model);
} else {
redirect("ro_manager/home");
}
}
}
After this you need to create you need to create a file name called form_validation in config folder. In that you need to write the validation rules as per user guide.
$config['login_form'] = array (
array
(
'key' => 'email',
'value' => 'Email',
'rule' => 'trim|required|valid_email|xss_clean'
),
array
(
'key' => 'passwd',
'value' => 'Password',
'rule' => 'trim|required|alpha_numeric|xss_clean'
)
);

Try like this way
$this->form_validation->set_rules('email', 'Email', 'required');
if ($this->form_validation->run() == FALSE){
$this->load->view('myform');
}else{
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if($this->form_validation->run() == FALSE){
$this->load->view('myform');
}
$this->load->view('formsuccess');
}

Related

Codeigniter - form_validation callback function error message

View:
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<form method="post" action="<?php echo base_url();?>account/register">
<?php $form_error = $this->session->flashdata('error'); ?>
<div class="form-group">
<label for="username">Username</label>
<input class="form-control" id="username" name="username" type="input">
<div id="form_error"><?php echo $form_error['username']; ?></div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" id="password" name="password" type="password">
<div id="form_error"><?php echo $form_error['password']; ?></div>
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password</label>
<input class="form-control" id="confirm_password" name="confirm_password" type="password">
<div id="form_error"><?php echo $form_error['confirm_password']; ?></div>
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select class="form-control" id="gender" name="gender">
<option disabled selected value="">select a gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<div id="form_error"><?php echo $form_error['gender']; ?></div>
</div>
<div class="form-group">
<label for="birthdate">Birthdate</label>
<input class="form-control" id="birthdate" name="birthdate" type="date">
<div id="form_error"><?php echo $form_error['birthdate']; ?></div>
</div>
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="<?php echo base_url();?>pages/login_user">Already have an account?</a>
</div>
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
Account Controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date');
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
echo 'aw';
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{
echo $birthdate;
$this->form_validation->set_message('valid_date', 'Invalid Birthdate');
$form_error['birthdate'] = form_error('valid_date');
$this->session->set_flashdata('error',$form_error);
return FALSE; }
}
Pages Controller:
public function login_user(){
$data['title'] = 'Login';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/login');
$this->load->view('template/footer');
}
public function register_user(){
$data['title'] = 'Register';
$this->load->view('template/header',$data);
$this->load->view('template/navbar');
$this->load->view('pages/registration');
$this->load->view('template/footer');
}
I tried setting flashdata inside the callback function but this is my first time using a callback function to check the validity of the birthdate given. I tested out the input and you can't input any alphabets but you can go over the maximum length. For example the format should be 'YYYY-MM-DD' you can input something like this: 555555-55-55.
All my other error prints out successfully but the valid_date callback function prints an error:
Unable to access an error message corresponding to your field name
Birthdate.(valid_date)
If what i'm asking for is impossible/wrong then i'll just add a min_length[10] and max_length[10] and just edit its error to 'invalid date'.
EDIT: Taking inspiration from my statement above about the max and min length, i also added a custom error for the valid_date there and what do you know it works.
Heres my updated controller:
public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date',
array('valid_date' => 'Invalid Date of birth'));
if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d',time()),
'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}
//form_validation callback
public function valid_date($birthdate){
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{return FALSE; }
}
I'm still not sure if it really works or just by fluke.
Register code:
public function register() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
if ($this->form_validation->run() == FALSE) {
// let's see what's going on under the hood...
print_r($this->form_validation->error_array());
exit;
$form_error = array('username' => form_error('username'),
'password' => form_error('password'),
'confirm_password' => form_error('confirm_password'),
'gender' => form_error('gender'),
'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
} else {
$data = array('username' => $this->input->post('username'),
'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT),
'gender' => $this->input->post('gender'),
'birthdate' => $this->input->post('birthdate'),
'date_created' => mdate('%Y-%m-%d', time()),
'last_login' => mdate('%Y-%m-%d', time()));
if ($this->account_model->create_account($data)) {
$this->session->set_flashdata('message', 'Registration Successful');
redirect('pages/login_user');
} else {
$this->session->set_flashdata('message', 'Registration Failed');
redirect('pages/register_user');
}
}
}
Referencing a callback necessitates the function be called via callback_func_name.
Revised callback:
Note: item does not start with callback_
See: Correctly determine if date string is a valid date in that format (read: test cases)
public function valid_date($date) {
$format = 'Y-m-d';
$d = DateTime::createFromFormat($format, $date);
if ($d && $d->format($format) == $date) {
return TRUE;
} else {
$this->form_validation->set_message('valid_date', 'Invalid Birthdate.');
return FALSE;
}
}
Doing date('YYYY-MM-DD') is wrong as it yields: 2018201820182018-FebFeb-SatSat. See date docs.
You should call this way:
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');
hey try this to use callback
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_validdate',
//form_validation callback
public function validdate($birthdate){
$birthdate = $this->input->post('birthdate');
if( date('YYYY-MM-DD',strtotime($birthdate)) )
{
return true;
}
$this->form_validation->set_message('validdate','Check the birthday input to match a format like this YYYY-MM-DD');
return false;
}
Callbacks: Your own Validation Methods
The validation system supports callbacks to your own validation methods. This permits you to extend the validation class to meet your needs. For example, if you need to run a database query to see if the user is choosing a unique username, you can create a callback method that does that
More Detail read https://codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

codeigniter form validation not displaying errors

I am using a wamp server on my local machine , to host my codeigniter project.
Everything seems to work well , but the form validation wont display the errors when one occur.
The callback to check if email already exist doesnt also work , which is really weird because it was working last night.
this is my controller -
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Signup extends MX_Controller
{
function __construct() {
parent::__construct();
//calling helpers and library classes from ci
$this->load->helper(array('form', 'url'));
$this->load->helper('date');
$this->load->library('form_validation');
}
public function index() {
// loading the registration form
$this->load->view('register');
// form validation
$this->form_validation->set_rules('username', 'Username', 'required|min_length[3]|max_length[12]|is_unique[gamers.username]');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|callback_isEmailExist');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('region', 'Region', 'required');
$this->form_validation->set_rules('dob', 'Birth Date', 'required');
$this->form_validation->set_rules('phone', 'Mobile Number', 'required');
$this->form_validation->set_rules('passphrase', 'Password', 'trim|required|sha1');
$this->form_validation->set_rules('referral', 'Referred By');
if ($this->form_validation->run() !== FALSE)
{
//loading model
$this->load->model('signup_model');
// preparing form data
$username = $this->input->post('username');
$email = $this->input->post('email');
$country = $this->input->post('country');
$region = $this->input->post('region');
$dob = $this->input->post('dob');
$phone = $this->input->post('phone');
$password = $this->input->post('passphrase');
$referred = $this->input->post('referral');
//check current time stamp
$join_date = date('Y-m-d H:i:s');
//email verification hush key-generator
$token = md5(rand(0,1000).'cashout233');
// packaging form data for transport in an array
$data = array(
'username' => $username,
'email' => $email,
'country' => $country,
'region' => $region,
'birthdate' => $dob,
'phone_number' => $phone,
'password' => $password,
'join_date' => $join_date,
'referral' => $referred,
'token' => $token
);
// finally transporting data to the model
$taxi = $this->signup_model->register_gamer($data);
if ($taxi !== false) {
// send email verification link after sucessfull transport
// $from = 'noreply#talenthut.com';
// $to = $email;
// $subject = 'Email Confirmation Instructions';
// $message = '
// '.$first_name.', Thanks for signing up!
// Please click this link to activate your account:
// localhost/index.php/email_verification?email='.$email.'&hash='.$hash.'
// '; // Our message above including the link
// $this->email->from($from);
// $this->email->to($email);
// $this->email->subject($subject);
// $this->email->message($message);
// $this->email->send();
// Redirect user to Email Confirmation Page
redirect('index.php/signup/EmailConfirmation/'.urlencode($email));
}
}
}
public function isEmailExist($str) {
$this->load->model('signup_model');
$is_exist = $this->signup_model->isEmailExist($str);
if ($is_exist) {
$this->form_validation->set_message(
'isEmailExist', 'Email address is already in use.'
);
return false;
} else {
return true;
}
}
public function EmailConfirmation($to)
{
echo "email has been sent to ".urldecode($to);
// loading the email confirmation page
// $this->load->view('e_confirmation');
}
}
My view that displays the registration form is -
<?php echo form_open('index.php/signup'); ?>
<!-- fieldsets -->
<fieldset>
<div class="errors"> <?php echo validation_errors(); ?> </div>
<label>
<input id="username" type="text" name="username" value="" placeholder="Username" />
</label>
<label>
<input id="email" type="email" name="email" value="" placeholder="Email" />
</label>
<label>
<select name="country"><br/>
<option value="Ghana">Ghana</option>
</select>
</label>
<label>
<select name="region"><br/>
<option value="">Choose Region...</option>
<option value="Greater Accra">Greater Accra</option>
<option value="Central">Central</option>
<option value="Western">Western</option>
<option value="Eastern">Eastern</option>
<option value="Ashanti">Ashanti</option>
<option value="Brong Ahaful">Brong Ahaful</option>
<option value="Northen">Northen</option>
<option value="Volta">Volta</option>
<option value="Upper East">Upper East</option>
<option value="Upper West">Upper West</option>
</select>
</label>
<label>
<input id="dob" type="text" name="dob" value="" placeholder="Birth Date" />
</label>
<label>
<input id="phone" type="text" name="phone" value="" placeholder="Mobile Number" />
</label>
<label>
<input id="password" type="password" name="passphrase" value="" placeholder="Password" />
</label>
<label>
<select name="referral"><br/>
<option value="">how did you know about us</option>
<option value="Search Engine">Search engine</option>
<option value="Twitter">Twitter</option>
<option value="Word of Mouth">Word of mouth</option>
<option value="Newspaper">Newspaper</option>
</select>
</label>
<label>
<span> </span>
<p class="help">By clicking the sign up button below, you confirm that you are 18 years , and you agree to our
Terms and Conditions and Privacy Policy.</p><br/><br/>
<span> </span>
<button class="submit" type="submit">Sigm Up</button>
</label>
</fieldset>
</form>
model function for the isEmailExist controller function is
function isEmailExist($email) {
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('gamer');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
Thanks in advance.
worked it out!!!
I realised the validations doesnt work with redirections but only views.
I also called the login form too early before the validation. I placed it in the if condition and everything worked like a charm .
As for the "callback " . I just had to eliminate all that nonsense and replaced it with is_unique.
You can check email exist or Not as simply applying codeigniter inbuild rule:
is_unique[table_name.table_coloum]
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|is_unique[users.email]');

Unique field in codeigniter

I need to make Unique Serial number SN in my form. I've tried to do it, but I can't understand how this function works. Please explain clearly as I'm new to programming with codeigniter
view:my view (form)
Branch: <input type="text" name="branch" /><br/>
Business Unit: <input type="text" name="buinessUnit" /><br/>
Device Type: <input type="text" name="deviceType" /><br/>
Brand: <input type="text" name="brand" /><br/>
Device Model: <input type="text" name="deviceModel" /><br/>
SN: <input type="text" name="SN" /><br/> //that i need unique
status: <input type="text" name="status" /><br/>
department: <input type="text" name="department" /><br/>
username: <input type="text" name="username" /><br/>
notes: <input type="textarea" name="notes" /><br/>
computername: <input type="text" name="computerName" /><br/>
Save:<input type="submit" name="save" />
</form>
</body>
</html>
model:to insert data into database
<?php
class add_model extends CI_Model {
public function insert_into_db(){
$post=$this->input->post();
//insert data with query builder
$data=array('Branch'=>$post['branch'],'BusinessUnit'=>$post['buinessUnit'],'DeviceType'=>$post['deviceType'],'Brand'=>$post['brand'],'DeviceModel'=>$post['deviceModel'],'SN'=>$post['SN'],'Status'=>$post['status'],'Departmant'=>$post['department'],'UserName'=>$post['username'],'Notes'=>$post['notes'],'ComputerName'=>$post['computerName']);
$this->db->insert('hardware_assets', $data);
return $this->db->insert_id(); // if using mysql
}
}
controller:to handle model and view
<?php
class Speed extends CI_Controller {
function insert_to_db()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('branch', 'Branch', 'trim|required|xss_clean');
$this->form_validation->set_rules('buinessUnit', 'BuinessUnit', 'trim|required|xss_clean');
$this->form_validation->set_rules('deviceType', 'DeviceType', 'trim|required|xss_clean');
$this->form_validation->set_rules('brand', 'Brand', 'trim|required|xss_clean');
$this->form_validation->set_rules('deviceModel', 'DeviceModel', 'trim|required|xss_clean');
$this->form_validation->set_rules('SN', 'SN', 'trim|required|xss_clean');
$this->form_validation->set_rules('status', 'Status', 'trim|required|xss_clean');
$this->form_validation->set_rules('department', 'Department', 'trim|required|xss_clean');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('notes', 'Notes', 'trim|required|xss_clean');
$this->form_validation->set_rules('computerName', 'ComputerName', 'trim|required|xss_clean');
/*
*/
if ($this->form_validation->run() == FALSE)
{
$this->load->view('pages/home');
}
else
{
$this->load->model('add_model');
$this->add_model->insert_into_db();
$this->load->view('pages/home');//loading success view
//$this->load->view('pages/formsuccess');
}
}
// 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;
// }
// }
}
check the link.
instead of user_name use serial no. it will work for both insert and update.
Replace Your this line,
$this->form_validation->set_rules('SN', 'SN', 'trim|required|xss_clean');
With,
$this->form_validation->set_rules('SN', 'SN', 'trim|required|xss_clean|is_unique[hardware_assets.SN]');
If you create your Own Function for UNIQUE SN then Used three Thing
$date = date("ymdhis");
$SD = rand(10,2000);
$ID =$this->db->insert_id();
$SN = $ID.SD.$date;
For Making Your Custom validation please add a file in your library folder my_form_validation.php as you can modify this function or create new one as per your requirement,
<?php
class MY_Form_validation extends CI_Form_validation {
//used to check unique value at update record
function unique($value, $params) {
$CI = & get_instance();
$CI->load->database();
$CI->form_validation->set_message('unique', 'The %s is already taken.');
list($table, $field, $id_field, $id) = explode(".", $params, 4);
$data = $CI->db->select($field)->from($table)
->where($field, $value)
->where($id_field . " != ", $id)
->get()->num_rows();
if ($data) {
return FALSE;
} else {
return TRUE;
}
}
}
?>

codeigniter - form submission mistake

i made a normal form for users to submit data name,email and city in form for this work i use some coding and i still not figure out where i mistaken please suggest.
routes
$route['default_controller'] = "welcome";
welcome.php in controller
public function index()
{
$this->load->view('ar_signup');
$this->load->helper('url');
}
}
ar_signup for the form in view
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Landing Page</title>
<meta charset="utf-8">
<link href="assests/css/ar/ar.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('user'); ?>
<label for="name">Name:</label>
<input type="name" id="name" name="name">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="city">City:</label>
<input type="city" id="city" name="city">
<input type="submit" value="Login">
</div>
</form>
</body>
</html>
user.php in controller
<?php
function create_member()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('city', 'City', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('ar_thanks');
}
else
{
$this->load->model('users_model');
if($query = $this->Users_model->create_member())
{
$this->load->view('ar_landing');
}
}
}
user_model.php mention in models
<?php
function create_member()
{
$this->db->where('user_name', $this->input->post('username'));
$query = $this->db->get('users');
if($query->num_rows > 0){
}else{
$new_member_insert_data = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'city' => $this->input->post('city'),
);
$insert = $this->db->insert('users', $new_member_insert_data);
return $insert;
}
}//create_member
}
In Your user.php controller change
if($this->form_validation->run() == FALSE)
{
$this->load->view('ar_thanks');
}
to
if($this->form_validation->run() == FALSE)
{
$this->load->view('ar_signup');
}
In your view file give this: <?php echo form_open('user/create_member'); ?>
Now hit the ur: localhost/landingpage/index.php/user/create_member
If your controller is 'welcome' then your url should be 'localhost/welcome'. Also check your mod_rewrite.
Edit
I think it will be your php installation, since you said when you removed the php codes, it was working perfectly.

Code Igniter form not posting

I have made a site in CodeIgniter2, but I can't get the forms to work, as I can't seem to even work out how to get it to post! Any help? Here is my code and the forms are only on the recommend, contact-us and support pages:
Form:
<div id="mainWhiteBox">
<h3>Tell people about us...</h3>
<p>If you know of a company or individual who need a really great design agency to help them with a project, let them know about us and benefit too. <br /><br />
<span class="customColour">We will give you £50 of Marks & Spencer vouchers for every client you recommend to us who goes on to become a client of xxxxx, it's that simple & there is no limit to the amount of vouchers you can earn!</span></p>
<div id="recommendSomeone">
<?php echo validation_errors(); print_r($_POST);?>
<?php echo form_open('recommend', array('id' => 'recommendForm')); ?>
<label for="friendName">Your Friend's Name</label>
<input type="text" id="friendName" value="<?php echo set_value('friendName'); ?>" />
<label for="friendEmail">Your Friend's Email Address</label>
<input type="email" id="friendEmail" value="<?php echo set_value('friendEmail'); ?>" placeholder="someone#youknow.com" />
<label for="customerName">Your Name</label>
<input type="text" id="customerName" value="<?php echo set_value('customerName'); ?>" />
<label for="customerEmail">Your Email Address</label>
<input type="email" id="customerEmail" value="<?php echo set_value('customerEmail'); ?>" placeholder="you#youremailaddress.com" />
<label for="friendConfirm"><input type="checkbox" id="friendConfirm" value="1" <?php echo set_checkbox('friendConfirm', '1'); ?> />I confirm that I know the person I am recommending above.</label>
<input type="submit" value="Submit Recommendation" />
</form>
<img src="<?=base_url(); ?>images/uploads/<?php echo $images[0]["image_filename"]; ?>" alt="<?php echo $images[0]["image_alt"]; ?>" width="180px" height="300px" class="floatRight" />
</div>
<p class="elevenFont">* Get £50 of Marks & Spencer vouchers per company or person recommended who goes on to open an account with xxxxx.</p>
</div>
<?php include("/home/xxxxx/libraries/application/views/widgets/newsWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/twitterWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/quickViewWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/fbLikePageWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/getQuoteBarWidget.php"); ?>
<?php include("/home/xxxxx/libraries/application/views/widgets/newsletterSubscribeWidget.php"); ?>
Controller:
<?php
class Pages extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('pages_model');
}
public function view($page = 'home')
{
if ( ! file_exists('/home/urbanfea/libraries/application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = $this->pages_model->getTitle($page);
$data['showcase'] = $this->pages_model->getShowcase();
$data['news'] = $this->pages_model->getNewsWidgetContent();
$data['quote'] = $this->pages_model->getQuoteFromBank();
$data['images'] = $this->pages_model->getPageImageArray($page);
$data['PageStraplines'] = $this->pages_model->getStraplines($page);
$data['serverStatus'] = $this->pages_model->getIssue("1");
if($page == "support")
{
$this->load->view('templates/supportHead', $data);
}
else
{
$this->load->view('templates/head', $data);
}
if($page == "recommend" || $page == "contact-us" || $page == "support")
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('friendName', 'Friend\'s Name', 'required');
$this->form_validation->set_rules('friendEmail', 'Friend\'s Email Address', 'required');
$this->form_validation->set_rules('customerName', 'Customer\'s Name', 'required');
$this->form_validation->set_rules('customerEmail', 'Customer\'s Email Address', 'required');
//$this->form_validation->set_rules(FriendConfirm', 'Confirm you know the person', 'required');
if ($this->form_validation->run() === true)
{
$this->load->view('templates/formSuccess', $data); echo "a";
}
elseif($this->form_validation->run() === false && validation_errors() != "")
{
$this->load->view('templates/formError', $data); echo "b";
}
elseif($this->form_validation->run() === false)
{
echo "c";
}
}
$this->load->view('templates/header', $data);
$this->load->view('pages/'.$page, $data);
$this->load->view('templates/footer', $data);
}
}
?>
Edit
Here are the routes in my router:
$route['404_override'] = '';
$route['user/(:any)'] = 'user/view/$1';
$route['user'] = 'user/login';
$route['our-work/(:any)'] = 'our_work/view/$1';
$route['our-work'] = 'our_work';
$route['what-we-do/(:any)'] = 'what_we_do/view/$1';
$route['what-we-do'] = 'what_we_do';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
Your form_open function echo form_open('recommend', array('id' => 'recommendForm')); will create the following output: <form method="post" accept-charset="utf-8" action="http:/example.com/index.php/recommend" />
This is looking for a controller called recommend, which I don't think is what you want. Change the form_open function so it directs your form to the proper controller/action.
Also, it doesn't look like your code is taking full advantage of the MVC framework. Instead of handling passing everything through the same controller/function and having all those if statements to load different views based on what $page is, you should have separate functions for each of those views.
EDIT:
Your form input elements are missing the name attribute. They must have the name attribute to be accessible through $_POST. Take a look at this page in the Codeigniter help. Maybe make use of the form_input function to generate the input fields?

Categories