codeigniter form validation not displaying errors - php

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]');

Related

How to validate emails listed for Companies/Clients that are stored in multiple fields?

I am trying to get emails that are listed in more than one field for companies/clients that are registered in my database tables to be validated when signing up on my site with the registered company/client email(s). I currently have one table for companies (tbl_companies) and one table for clients (tbl_clients) where I store the emails for both that are listed in the email, email1, and email2 fields via my admin panel. Once the emails listed are stored in either table the company/client then registers the email(s) listed for them via a company_signup form, which sends them an email with a verification link to verify their access to their company/client admin panel to modify their profiles.
The issue I am having is currently after listing all of the emails for the companies/clients in both of the tables the company_signup form only sees the emails that are in the email field for tbl_companies (email) and tbl_clients (email). I would like it to see both the email, email1, and email2 field from tbl_companies and tbl_clients when the company_signup form checks for the email being validated for registration and verification.
So far I have tried SELECT *, UNION, JOIN, and WHERE for SQL functions to try merging the tbl_companies and tbl_clients together using their ability to call more than one field in the two table to have them checked.
I have the functions called in a class.php which is included in both the company_form.php, client_form.php of my admin panel and company_signup.php of my signup form.
This is the code from my class.php page
public function get_email_artist($email){
$this->sql = "SELECT * FROM tbl_music_artists WHERE email ='{$email}'
OR email1 ='{$email}'
OR email2 ='{$email}'";
$this->data = $this->fetch_row_assoc($this->sql);
if(!empty($this->data))
return $this->data;
else{
return false;
}
}
public function get_email_company($email){
$this->sql = "SELECT * FROM tbl_music_companies WHERE email ='{$email}'
OR email1 ='{$email}'
OR email2 ='{$email}'";
$this->data = $this->fetch_row_assoc($this->sql);
if(!empty($this->data))
return $this->data;
else{
return false;
}
}
public function get_company_email($email){
$this->sql = "SELECT * FROM login WHERE email ='{$email}'";
$this->data = $this->fetch_row_assoc($this->sql);
print_r($this->data);exit;
if(!empty($this->data)){
return $this->data;
}
else{
$sql = "(SELECT email, email1, email2 FROM tbl_music_artists WHERE email ='{$email}'
OR email1 ='{$email}'
OR email2 ='{$email}')
UNION
(SELECT email, email1, email2 FROM tbl_music_companies WHERE email ='{$email}'
OR email1 ='{$email}'
OR email2 ='{$email}')
";
$data = $this->fetch_row_assoc($sql);
if(!empty($data)){
return false;
}
return true;
}
}
public function register_company($inputs)
{
if(is_array($inputs)){
// $pwdHasher = new PasswordHash(8, FALSE);
// $hash is what you would store in your database
// $hash = $pwdHasher->HashPassword( $_POST['com_password'] );
$hash = base64_encode($_POST['com_password']);
$uname = preg_replace('/#.*?$/', '', $_POST['com_email']);
$uname .= rand();
$input_array = array(
'email' => trim($_POST['com_email']),
'u_type' => 'company',
'password' => $hash,
'username' => $uname,
'name ' => ucwords($_POST['com_name']),
'phone' => $_POST['com_phone'],
'city ' => $_POST['com_city'],
'country' => $_POST['com_country'],
'website' => $_POST['com_url'],
'gender' => $_POST['com_gender'],
'security_question' => $_POST['com_quest'],
'security_answer' => $_POST['com_ans'],
'status' => 0,
);
$data = $this->get_email_artist(trim($_POST['com_email']));
if($data) {
$this->sendRegisterEmailCompany(array($data[email],$data[email1],$data[email2]), ucwords($_POST['com_name']));
return $this->insert($input_array, 'login');
}
else {
$data = $this->get_email_company(trim($_POST['com_email']));
if($data) {
$this->sendRegisterEmailCompany(array($data[email],$data[email1],$data[email2]), ucwords($_POST['com_name']));
return $this->insert($input_array, 'login');
}
else{
return 'invalid input';
}
}
}
else{
return 'invalid input';
}
}
public function sendRegisterEmailCompany($email, $name)
{
// ini_set("SMTP","smtp.vianet.com.np");
// ini_set("smtp_port","25");
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']) . '/company_validate.php?identifier=' . base64_encode($email);
$message = '<html><body>';
$message .= '<h1>World Music Listing</h1>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td>Dear {$name},<br /> You have signed up successfully in the wml guide directory.<br />Before we can proceed please <strong>confirm</strong> your email address. <a href='$url'>Click here</a> OR copy below url and paste into your browser</td></tr>";
$message .= "<tr style='background: #eee;'><td>$url</td></tr>";
$message .= "<tr style='background: #eee;'><td>With Regards, <br />World Music Listing</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$to = $email;
$subject = 'Company Sign up successful notification- WML Guide';
$headers = "From: " . $email . "\r\n";
$headers .= "Reply-To: ". $email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
This is the code in my ajax.php
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// Select all artists (clients) and order by name //
$sql = "SELECT email, email1, email2
FROM tbl_music_artists
WHERE email ='{$com_email}' OR email1 = '{$com_email}' OR email2 = '{$com_email}'
UNION
SELECT email, email1, email2
FROM tbl_music_companies
WHERE email ='{$com_email}' OR email1 = '{$com_email}' OR email2 = '{$com_email}'";
$data = $this->fetch_row_assoc($sql);
if(!empty($data)){
$valid = true;
echo json_encode($valid);
}
else{
echo json_encode($valid);
}
};
This is the code for my company_signup page
<div class="tab-content">
<div id="page-heading">
<h1>World Music Listing Company Registration</h1>
<hr />
</div>
<div id="tab1" class="tab active">
<?php if(isset($_SESSION['error'])) { ?>
<div class="alert alert-error"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
<?php } ?>
<form class="form-style-1" id="register" method="POST" action="signupcompanycontroller.php">
<ul class="form-style-1">
<li class="bottom"><label>Account Details</label></li>
<li>
<label>Email <span class="required">*</span></label>
<input type="email" name="com_email" class="field-long" placeholder="enter your email address" size="50" required />
</li>
<li>
<label>Password <span class="required">*</span></label>
<input type="password" name="com_password" class="field-long" placeholder="enter password" size="50" required id="password" />
</li>
<li>
<label>Confirm Password <span class="required">*</span></label>
<input type="password" name="com_conpassword" class="field-long" placeholder="enter confirm password" size="50" required />
</li>
<li class="bottom"><label>Personal Details</label></li>
<li>
<label>Full Name <span class="required">*</span></label>
<input type="text" name="com_name" class="field-long" placeholder="enter your full name" size="50" required />
</li>
<li>
<label>Phone <span class="required">*</span></label>
<input type="text" name="com_phone" class="field-long" placeholder="enter your phone number" size="50" required />
</li>
<!-- <li>
<label>Street Address</label>
<input type="text" name="com_address" class="field-long" placeholder="enter your Street Address" size="50" />
</li> -->
<li>
<label>City <span class="required">*</span></label>
<input type="text" name="com_city" class="field-long" placeholder="enter your city name" size="50" required />
</li>
<li>
<label>Country <span class="required">*</span></label>
<select name="com_country" class="field-divided" required>
<option value="">Select One</option>
<?php
$country_list = country();
foreach ($country_list as $key => $value) {
if(!empty($value))
echo '<option>' . $value . '</option>';
}
?>
</select>
</li>
<li>
<label>Website</label>
<input type="url" name="com_url" class="field-long" placeholder="enter website url" size="50" />
</li>
<li>
<label>Gender</label>
<select name="com_gender" class="field-divided">
<option value="">Select One</option>
<option>Male</option>
<option>Female</option>
</select>
</li>
<li class="bottom"><label>Security</label></li>
<li>
<label>Security Question <span class="required">*</span></label>
<select name="com_quest" class="field-long" required>
<option value="">Select One</option>
<option value="What is the name of your favorite pet?">What is the name of your favorite pet?</option>
<option value="What is your preferred musical genre?">What is your preferred musical genre?</option>
<option value="What is the street number of the house you grew up in">What is the street number of the house you grew up in?</option>
<option value="What time of the day were you born?">What time of the day were you born?</option>
<option value="What is the name of your favorite childhood friend?">What is the name of your favorite childhood friend?</option>
<option value="What is the name of the company of your first job?">What is the name of the company of your first job?</option>
<option value="What is the middle name of your oldest sibling?">What is the middle name of your oldest sibling?</option>
<option value="What is the middle name of your oldest child?">What is the middle name of your oldest child?</option>
<option value="What was the last name of your third grade teacher?">What was the last name of your third grade teacher?</option>
<option value="What was your childhood nickname?">What was your childhood nickname?</option>
<option value="What is your spouse’s mother’s maiden name?">What is your spouse’s mother’s maiden name?</option>
<option value="What is your mother’s maiden name?">What is your mother’s maiden name?</option>
<option value="What was your high school mascot?">What was your high school mascot?</option>
</select>
</li>
<li>
<label>Answer</label>
<input type="text" name="com_ans" class="field-long" placeholder="enter your answer" size="50" required />
</li>
<li class="bottom"><label>Terms and Mailing</label></li>
<li>
<label class="term"><input type="checkbox" name="com_terms" value="1" required class="condition"> <span class="required">*</span> <span id="terms">I accept the Terms and Conditions</span></label>
<!-- <label><input type="checkbox" name="com_offer" value="1"> I want to receive personalized offers by your site</label>
<label><input type="checkbox" name="com_offer_partner" value="1"> Allow partners to send me personalized offers and related services</label> -->
</li>
<li>
<label> </label>
<input type="submit" value="Register" id="form_submit" />
</li>
</ul>
</form>
</div>
</div>
</div>
</div>
<div id="termscondition" style="display: none;" title="Terms and Conditions">
A. By using or visiting the World Music Listing website or any World Music Listing products, software, data feeds, including but not limited to its music/entertainment directory/list of contacts, and services provided to you on, from, or through the World Music Listing website (collectively the "Service") you signify your agreement to (1) these terms and conditions (the "Terms of Service"), (2) World Music Listing's Privacy Policy, found at http://www.wmlmusicguide.com/terms.php and incorporated herein by reference, and (3) World Music Listing's Community Guidelines, found at http://www.wmlmusicguide.com/terms.php and also incorporated herein by reference. If you do not agree to any of these terms, the World Music Listing Privacy Policy, or the Community Guidelines, please do not use the Service.
Please read more
</div>
<!-- end content-outer......END -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="public/js/jquery.validate.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$().ready(function(){
$('#register').validate({
rules: {
com_email: {
required: true,
email: true,
remote: 'ajax_company.php'
},
com_password: {
minlength: 6,
required: true
},
com_conpassword: {
equalTo : '#password;'
},
com_name: {
minlength: 3,
required: true
},
com_phone: {
required: true
},
com_city: {
required: true
},
com_country: {
required: true
},
com_quest: {
required: true
},
com_ans: {
required: true
},
com_terms: {
required: true
}
},
messages: {
com_email: {
remote: 'Entered email address not found.'
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
if (element.attr('type') == 'checkbox') {
error.insertAfter($('.term'));
} else {
error.insertAfter(element);
}
}
});
$('.condition').click(function () {
if ($(this).is(':checked')) {
$('#termscondition').dialog({
modal: true,
width: 600,
buttons: {
Ok: function() {
$( this ).dialog('close');
}
}
});
} else {
$('#termscondition').dialog('close');
}
});
});
</script>
The issue seems to be that you are only selecting against the first email field. If you want to check against all email fields you need to update your WHERE condition like so:
$sql = "SELECT email, email1, email2
FROM tbl_music_artists
WHERE email ='{$com_email}' OR email1 = '{$com_email}' OR email2 = '{$com_email}'
UNION
SELECT email, email1, email2
FROM tbl_music_companies
WHERE email ='{$com_email}' OR email1 = '{$com_email}' OR email2 = '{$com_email}'
EDIT:
This function:
$data = $this->get_email_artist(trim($_POST['com_email']));
Must return all the email addresses.
Then this function needs to email all the addresses:
$this->sendRegisterEmailCompany(trim($_POST['com_email']), ucwords($_POST['com_name']));
At the moment it just sends to the $_POST['com_email']. It depends on that function but you should be able to pass it an array of the email addresses ie:
$this->sendRegisterEmailCompany(array($data['email1'],$data['email2'],$data['email3']), ucwords($_POST['com_name']));

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;
}
}
}
?>

how to validate form in a order codeigniter

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');
}

controller/form doing strange things when content is implemented

I have the controller below and I would like it do the following things:
Show an error if the username is taken -> currently just submits as
normal even through the specific user is in the database.
Populate with data if there was an error -> currently populates with
the imported data if correct
Keep active state of the selected drop down menu item
View:
<h1><?php echo $companyName; echo nbs(1);?> - <?php echo $pageTitle; ?></h1>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<p>Error: <?php echo validation_errors();?></p>
<div class="formContent">
<form action="createUser" method="post">
<fieldset class="control-group">
<label for="userName">User Name:</label><input type="text" id="userName" name="userName" value="<?php echo set_value('userName'); ?>" placeholder="User Name">
<label for="userPassword">User Password:</label><input type="password" id="userPassword" name="userPassword" value="<?php echo set_value('userPassword'); ?>" placeholder="User Password">
<label for="userFirstName">First Name:</label><input type="text" id="userFirstName" name="userFirstName" value="<?php echo set_value('userFirstName'); ?>" placeholder="First Name">
<label for="userLastName">Last Name:</label><input type="text" id="userLastName" name="userLastName" placeholder="Last Name">
<label for="userEmail">E-Mail:</label> <input type="text" id="userEmail" name="userEmail" placeholder="Admin E-mail">
<label for="userGroup"> User Group:</label>
<select name="userGroup" id="userGroup">
<option value="select">Please Select</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
<label for="userActive"> User Active:</label>
<select name="userActive" id="userActive">
<option value="select">Please Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
<div>
<button type="submit" class="btn-primary">Create</button>
</div>
</fieldset>
</form>
</div>
Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class createUser extends CI_Controller {
public function index()
{
//Form Validation prep making sure its all clean
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
//If form validation fails load previous page with errors else do the job and insert data into db
if($this->form_validation->run() == FALSE)
{
$data['success'] = "";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$group = $this->input->post('userGroup');
$active = $this->input->post('userActive');
$passwordHash = $this->encrypt->sha1($password); // Lets encrypt the password why sha1? MD5 is for tossers
// If the data is correct follow through with db insert
if($this->users_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
}
}
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
}
/* End of file login.php */
/* Location: ./application/controllers/admin/createUser.php */
If I were you, I would use a callback ( http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks )
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback__checkUsername');
as for your select drop downs, use the set_value() function
<select name="userGroup" id="userGroup">
<option value="select"<?=(set_value('userGroup')=='select')?' selected="selected"':''?>>Please Select</option>
<option value="admin"<?=(set_value('userGroup')=='admin')?' selected="selected"':''?>>Admin</option>
<option value="user"<?=(set_value('userGroup')=='user')?' selected="selected"':''?>>User</option>
</select>
Good luck
I am going at this purely from a logical php point as I know nothing about codeigniter
With regards to checking if a username is already taken, I would do a an db query on the username field in your "users" table and see if the name exists.
I see you have done this:
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');
I dont know the standard for referencing db tables in igniter, but maybe you are referencing the fields incorrectly. Also I would change every to lowercase while checking to ensure that you check is not case sensitive... unless you want case sensitive usernames.

Not outputting form error messages

I have a form that is not outputting any error messages have I missed something?
Model:
function createUser($username = NULL ,$passwordHash = NULL ,$firstname = NULL ,$lastname = NULL ,$email = NULL,$group = NULL ,$active = NULL)
{
$data = array('userName' => $username, 'userFirstName' => $firstname, 'userLastName' => $lastname, 'userEmail' => $email, 'userPassword' => sha1($passwordHash), 'userGroup' => $group, 'userActive' => $active);
$this->db->insert('users',$data);
return TRUE;
}
View:
<h1><?php echo $companyName; echo nbs(1);?> - <?php echo $pageTitle; ?></h1>
<?php
if($success == TRUE) {
echo '<section id = "validation">Page Updated</section>';
}
?>
<p>Error: <?php echo validation_errors();?> </p>
<div class="formContent">
<form action="createUser" method="post">
<fieldset class="control-group">
<label for="userName">User Name: <input type="text" name="userName" value="<?php echo set_value('userName'); ?>" placeholder="User Name"></label>
<label for="userPassword">User Password: <input type="password" name="userPassword" value="<?php echo set_value('userPassword'); ?>" placeholder="User Password"></label>
<label for="userFirstName">First Name: <input type="text" name="userFirstName" value="<?php echo set_value('userFirstName'); ?>" placeholder="First Name"></label>
<label for="userLastName">Last Name: <input type="text" name="userLastName" value="<?php echo set_value('userLastName'); ?>" placeholder="Last Name"></label>
<label for="userEmail">E-Mail: <input type="text" name="userEmail" value="<?php echo set_value('userEmail'); ?>" placeholder="Admin E-mail"></label>
<label for="userGroup"> User Group:
<select name="userGroup" value="<?php echo set_value('userGroup'); ?>">
<option value="select">Please Select</option>
<option value="admin">Admin Group</option>
<option value="user">User Group</option>
</select>
</label>
<label for="userActive"> User Active:
<select name="userActive" value="<?php echo set_value('userActive'); ?>">
<option value="select">Please Select</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</label>
<button type="submit" class="btn-primary">Create</button>
</fieldset>
</form>
</div>
Controller:
public function index()
{
$data['companyName'] = $this->core_model->companyName();
$data['success'] ="";
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
if($this->input->post('submit'))
{
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['companyName'] = $this->core_model->companyName();
$data['success'] ="";
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}else{
$username = $this->input->post('userName',TRUE);
$password = $this->input->post('userPassword', TRUE);
$firstname = $this->input->post('userFirstName', TRUE);
$lastname = $this->input->post('userLastName',TRUE);
$email = $this->input->post('userEmail',TRUE);
$group = $this->input->post('userGroup',TRUE);
$active = $this->input->post('userActive', TRUE);
$this->db->escape($username);
$this->db->escape($password);
$this->db->escape($firstname);
$this->db->escape($lastname);
$this->db->escape($email);
$this->db->escape($group);
$this->db->escape($active);
$passwordHash = $this->encrypt->sha1($password);
if ($this->core_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}else{
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
}
}
}
function __username_check($userName){
{
if ($userName == $user->$userName) {
$this->form_validation->set_message('username_check','Sorry the chosen username %s is taken!');
return false;
}else{
return true;
}
}
}
}
/* End of file login.php */
/* Location: ./application/controllers/admin/createUser.php */
You need to place the <input>s outside the <label> </label> tags! This is the main issue.
Also:
there's no input named "submit": your submit button, in fact, has no name attribute. And, btw, since you're already using form_validation class, that check (if input->post('submit')) is redundant;
Another redundant thing I see is passing TRUE (i.e., having it xss_cleaned) to the input->post method: you already have plenty of xss_clean validation rules, so why passing it again in that expensive extra processing, when already passed through it during validation check?
Sidenote, if you're using Active Record, or query bindings, you don't have to escape variables, so I'd remove that part too :)
And I believe your call to __username_check() will fail: the function, as for what concern the "callback_" validation rule, is "username_check"; and besides the double underscore is usually used for "magic methods" in PHP; you can safely remove both, or if you really want an underscore on the function name (just one) you might want to call "callback__check_username".
And you're loading the same views three times, why? I believe you can rewrite the whole index method like this:
function index()
{
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|xss_clean|callback_username_check');
$this->form_validation->set_rules('userPassword', 'User Password', 'trim|required|xss_clean|sha1');
$this->form_validation->set_rules('userFirstName', 'First Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userLastName', 'Last Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('userEmail', 'E-Mail', 'trim|required|xss_clean');
$this->form_validation->set_rules('userGroup', 'User Group', 'trim|required|xss_clean');
$this->form_validation->set_rules('userActive', 'User Active', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['success'] ="";
}else{
$username = $this->input->post('userName');
$password = $this->input->post('userPassword');
$firstname = $this->input->post('userFirstName');
$lastname = $this->input->post('userLastName');
$email = $this->input->post('userEmail');
$group = $this->input->post('userGroup');
$active = $this->input->post('userActive');
$passwordHash = $this->encrypt->sha1($password);
if ($this->core_model->createUser($username,$passwordHash,$firstname,$lastname,$email,$group,$active))
{
$data['success'] = TRUE;
}
}
$data['companyName'] = $this->core_model->companyName();
$data['pageTitle'] = "Create User";
$this->load->view('admin/assets/header', $data);
$this->load->view('admin/createUser', $data);
$this->load->view('admin/assets/footer');
}
UPDATE:
as for the username check, since v.2.0 of CodeIgniter you have that ability featured among the validation rules: if you place the is_unique rule, in fact, it will automatically query the database to check for that. The syntax is:
is_unique[table.field]
In your case, might be
$this->form_validation->set_rules('userName', 'User Name', 'trim|required|is_unique[users.userName]|xss_clean');

Categories