Codeigniter- How to preserve form values if error on submit - php

I have the form field like
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php if($user->postal_code === NULL) { echo set_value('postal_code');} else { echo $user->postal_code;} ?>">
<label for="form_control_1">Postal Code</label>
<span class="help-block">Postal Code is required</span>
and my function is
public function postProfile() {
if ($_POST) {
$this->form_validation->set_rules('postal_code', 'Postal Code', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'required');
$this->form_validation->set_rules('country', 'Country', 'required');
$this->form_validation->set_rules('month', 'Month', 'required');
$this->form_validation->set_rules('day', 'Day', 'required');
$this->form_validation->set_rules('year', 'Year', 'required');
$this->form_validation->set_rules('mobile_number', 'Mobile Number', 'required');
if ($this->form_validation->run() === FALSE) {
//$this->session->set_flashdata('err', validation_errors());
$this->session->set_flashdata('email_err', form_error('email'));
$this->session->set_flashdata('postal_code_err', form_error('postal_code'));
$this->session->set_flashdata('gender_err', form_error('gender'));
$this->session->set_flashdata('country_err', form_error('country'));
$this->session->set_flashdata('day_err', form_error('day'));
$this->session->set_flashdata('year_err', form_error('year'));
$this->session->set_flashdata('month_err', form_error('month'));
$this->session->set_flashdata('mobile_err', form_error('mobile_number'));
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
$dob = $this->input->post('month') . '/' . $this->input->post('day') . '/' . $this->input->post('year');
$userData = array(
'email' => $this->input->post('email'),
'date_of_birth' => $dob,
'gender' => $this->input->post('gender'),
'country' => $this->input->post('country'),
'mobile_number' => $this->input->post('mobile_number'),
'postal_code' => $this->input->post('postal_code'),
);
$updateUser = $this->user->updateUser($this->session->userdata['front']['id'], $userData);
if ($updateUser) {
$this->session->set_flashdata('err', '<div class="alert alert-success">Profile Updated Successfuly</div>');
redirect('profile/' . $this->session->userdata['front']['id']);
} else {
echo "Un expected error ";
exit;
}
}
} else {
$this->logout();
}
}
but value is not shown for the postal code field in case of validation errors

When error occur then you need to render view instead of rediect().
if ($this->form_validation->run() == FALSE) {
// no need to set_flashdata here for form_error()
$this->load->view('view_form',$data);
return;
}else{
//success code
}
Now view file
<input type="text" class="form-control" name="postal_code" id="form_control_1" value="<?php echo set_value('postal_code');?>">
<?php echo form_error('postal_code','<p class="alert alert-danger">','</p>');?>
Now your form will repopulate previous data if any error occur. In the same time you will see error message under your postal_code field

You can set these values in flashdata and redirect to your form. For example
if ($this->form_validation->run() == FALSE) {
$data = array(
'errors' => validation_errors(),
'name' => $this->input->post('name')//check this
);
$this->session->set_flashdata($data);
redirect('YOUR-URL-HERE');
}
And in your form use value attribute of form input as given below
<input type="text" class="form-control" name="name" placeholder="Name" value="<?= $this->session->flashdata('name'); ?>">

Related

Upload File Codeigniter,can't detect variabel

I'm trying to make upload image function on Codeigniter. but, when I trying to insert the image to the database. the variable can't be detected.
Here is my controller :
public function registrasi() {
//VALIDATION
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tb_m_user.email]');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]|matches[konfirmasi_password]');
$this->form_validation->set_rules('konfirmasi_password', 'Retype Password', 'required|trim|matches[password]');
if($this->form_validation->run() == false) {
$this->session->set_flashdata('fail' , 'Registration Failed! Please Try Again');
$this->load->view('auth/registrasi');
}else{
//INSERT TO DATABASE
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
$pict = $_FILES['pict'];
//LIBRARY UPLOAD CONFIG
$config['upload_path'] = '/assets/dist/foto_validasi';
$config['allowed_types'] = 'jpg|png';
$config['file_name'] = date('ymd');
$this->load->library('upload', $config);
if(!$this->upload->do_upload('pict')){
echo "Upload Failed";
}else{
$pict = $this->upload->data('file_name');
}
$data = [
'user_name' => $username,
'email' => $email,
'password' => $password,
'role' => 'pengguna',
'img' => $pict,
'status_aktivasi' => 'tidak aktif',
'created_by' => 'SYSTEM',
];
$this->m_auth->registrasi($data, 'tb_m_user');
$this->session->set_flashdata('success' , 'Registration Successful! Please Login');
Redirect('Auth/login');
}
}
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('auth/login');
}else{
$this->postlogin();
}
}
Here is my form View :
<?= form_open_multipart('Auth/registrasi'); ?>
<div class="border-top mt-3">
<div class="ml-2">
<label class="mt-2">Upload Kartu Identitas</label>
</div>
<div class="input-group mb-3">
<input type="file" class="form-control" placeholder="Upload Foto Identitas" name="pict">
<div class="input-group-append">
<div class="input-group-text">
<span class="fas fa-file-image"></span>
</div>
</div>
</div>
<small class="text-danger"><?= form_error('foto') ?></small>
</div>
<?= form_close(); ?>
Here is the error : error
I even tried to change the variabel from:
$pict = $this->upload->data('file_name');
'img' => $pict,
to :
$pict2 = $this->upload->data('file_name');
'img' => $pict2,
but it gets another error :error2
If you want the upload feature to be required, you could modify the codes like this :
public function registrasi() {
//VALIDATION
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tb_m_user.email]');
$this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[3]|matches[konfirmasi_password]');
$this->form_validation->set_rules('konfirmasi_password', 'Retype Password', 'required|trim|matches[password]');
if($this->form_validation->run() == false) {
$this->session->set_flashdata('fail' , 'Registration Failed! Please Try Again');
$this->load->view('auth/registrasi');
}else{
//INSERT TO DATABASE
$username = $this->input->post('username');
$email = $this->input->post('email');
$password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
$pict = $_FILES['pict'];
//LIBRARY UPLOAD CONFIG
$config['upload_path'] = '/assets/dist/foto_validasi';
$config['allowed_types'] = 'jpg|png';
$config['file_name'] = date('ymd');
$this->load->library('upload', $config);
if(!$this->upload->do_upload('foto')){
echo "Upload Failed";
$this->session->set_flashdata('fail', $this->upload->display_errors() );
redirect( 'auth/registrasi' );
}else{
$pict = $this->upload->data('file_name');
$data = [
'user_name' => $username,
'email' => $email,
'password' => $password,
'role' => 'pengguna',
'img' => $pict,
'status_aktivasi' => 'tidak aktif',
'created_by' => 'SYSTEM',
];
$this->m_auth->registrasi($data, 'tb_m_user');
$this->session->set_flashdata('success' , 'Registration Successful! Please Login');
Redirect('Auth/login');
}
}
}
The $this->upload->display_errors() code will display the error message on the uploaded file that does not meet the requirements, so if the file is not uploaded then the registration data will not be saved.
Change the post field name as if(!$this->upload->do_upload('pict')){
if(!$this->upload->do_upload('pict')){ // You should change this
size attribute should be there in input field
<input type="file" size="1" class="form-control" placeholder="Upload Foto Identitas" name="pict">

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

How to display the error on each fields in codeigniter

$this->form_validation->set_rules('username', 'User Name', 'required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('fname', 'Full Name', 'required|min_length[4]');
$this->form_validation->set_rules('user_password', 'Password', 'required|matches[confirm_password]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'required');
$this->form_validation->set_rules('cname', 'College Name', 'required');
$this->form_validation->set_rules('dob', 'Date of Birth', 'required|callback_valid_date');
$this->form_validation->set_rules('addr', 'Address', 'required');
$this->form_validation->set_rules('contact', 'Contact', 'required|min_length[10]|max_length[10]');
$this->form_validation->set_rules('education', 'Education', 'required');
$this->form_validation->set_rules('user_email', 'Email', 'required|valid_email|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('result', validation_errors());
redirect('login/register');
}
else
{
$rr = $this->user->register_user();
$this->session->set_flashdata('result', $rr);
redirect('login/register');
}
}
basically using $this->session->flashdata("result"); to show the result but i want each filed seprately validate i have tried form_error("field name "); but it's not working displaying empty result
Instead of redirecting, try to load the same form if there are any validation errors.
In your controller page.
function your_function(){
// load form helper
$this->load->helper(array('form', 'url'));
// load form validation library
$this->load->library('form_validation');
// validation rules
$this->form_validation->set_rules('username', 'User Name', 'required|min_length[4]|is_unique[users.username]');
$this->form_validation->set_rules('fname', 'Full Name', 'required|min_length[4]');
// check form for validations
if ($this->form_validation->run() == FALSE){
// load the same form/view
$this->load->view('myform');
} else{
// redirect to success page
}
}
In view page: can use the form_error() function to show an error message next to each form field
<?php echo form_error('username'); ?>
<input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" />
<?php echo form_error('fname'); ?>
<input type="text" name="fname" value="<?php echo set_value('fname'); ?>" size="50" />

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

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