codeigniter how to submit multiple rows with the same name - php

I have tried the following model view controller but i need to submit multiple rows at a time: please can any one help me how to achieve this?
this is my controller:
function add_item(){
$this->form_validation->set_rules('item_name', 'Item Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->model('mdl_item');
$data['main_content'] = 'backend/items/add_item';
$data['title'] = 'Create item';
$this->load->view('includes/template', $data);
}
else
{
$this->load->model('mdl_item');
$data = $this->input->post();
$this->mdl_item->create_item($data);
$this->session->set_flashdata('message', 'Items successfully created');
redirect('admin/items', 'refresh');
}
}
this is my model:
function create_item($data)
{
$data['expiry_date'] = date('Y-m-d', strtotime(element('expiry_date', $data)));
$crop_data = elements(array(
'item_name',
), $data);
$add_item = $this->db->insert_string('items', $crop_data);
$this->db->query($add_item);
}
this is my View:
<?php echo form_open('admin/items/add_item', 'id="item_form_validate"'); ?>
<div class="col-sm-12 col-md-12 jumbotron">
<input type="text" class="form-control" name="item_name[]" value="<?php echo set_value('item_name'); ?>">
<input type="text" class="form-control" name="item_name[]" value="<?php echo set_value('item_name'); ?>">
<input type="text" class="form-control" name="item_name[]" value="<?php echo set_value('item_name'); ?>">
<button type="submit" class="btn btn-success" value="submit"><span class="icon-checkmark"></span> <?php echo lang('Submit'); ?></button>
</form>

change the code set_rules('item_name', in Controllers
...
function add_item(){
$this->form_validation->set_rules('item_name', 'Item Name', 'trim|required');
to this set_rules('item_name[]'
...
function add_item(){
$this->form_validation->set_rules('item_name[]', 'Item Name', 'required');
and trim the value after you pass it

Related

Codeigniter 3 blog application: redirecting to the updated post fails

I am working on a basic (just 2 tables: authors and posts) blog application in Codeigniter 3.1.8.
I have an edit post functionality, using an update form:
<?php echo form_open("posts/update"); ?>
<input type="hidden" name="id" id="pid" value="<?php echo $post->id; ?>">
<div class="form-group <?php if(form_error('title')) echo 'has-error';?>">
<input type="text" name="title" id="title" class="form-control" placeholder="Title" value="<?php echo $post->title; ?>">
<?php if(form_error('title')) echo form_error('title'); ?>
</div>
<div class="form-group <?php if(form_error('desc')) echo 'has-error';?>">
<input type="text" name="desc" id="desc" class="form-control" placeholder="Short decription" value="<?php echo $post->description; ?>">
<?php if(form_error('desc')) echo form_error('desc'); ?>
</div>
<div class="form-group <?php if(form_error('body')) echo 'has-error';?>">
<textarea name="body" id="body" cols="30" rows="5" class="form-control" placeholder="Add post body"><?php echo $post->content; ?></textarea>
<?php if(form_error('body')) echo form_error('body'); ?>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
In the Posts_model model I have the method responsible with updating the post:
public function update_post() {
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body')
];
$this->db->where('id', $this->input->post('id'));
return $this->db->update('posts', $data);
}
In the Posts controller, I have 2 methods, for editing and updating the post:
public function edit($id) {
$data = $this->Static_model->get_static_data();
$data['post'] = $this->Posts_model->get_post($id);
$data['tagline'] = 'Edit the post "' . $data['post']->title . '"';
$this->load->view('partials/header', $data);
$this->load->view('edit');
$this->load->view('partials/footer');
}
public function update() {
$this->Posts_model->update_post();
// Redirect to the updated post
}
In my update() method, I was unable to redirect to the updated post. The redirect($this->agent->referrer()); line only brings me back to the update form. Where I want to redirect to is the just updated post. How do I do that?
Post vars should be handled in your controller:
public function update() {
$id = $this->input->post('id');
$data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('desc'),
'content' => $this->input->post('body')
];
// Update post
$this->Posts_model->update_post($id, $data);
// Redirect to the updated post
redirect('posts/post/' . $id);
}
Model:
public function update_post($id, $data) {
$this->db->where('id', $id);
return $this->db->update('posts', $data);
}
Note: if you want to do it your way, then simply return the id in the model function and redirect based on the return of the function in update()

codeigniter pass data from view to controller

I encountered problem with codeigniter. I want to update my profile page. I have problem when passing data from textbox in view to controller. In controller Profile.php, i have print_r $data that show no data get from view. Hope you guys can help me. Thank you.
View profile.php
if(isset($profile)){
?>
<?php echo validation_errors();?>
<?php echo form_open('profile/update_profile'); ?>
<div class="field half first"><input type="password" name="pass" placeholder="Password" value="<?php echo $profile['password']; ?>" /></div>
<div class="field half"><input type="password" name="con_pass" placeholder="Confirm Password" value="<?php echo $profile['con_password']; ?>" /></div>
<div class="field half"><input type="text" name="phone_no" placeholder="Phone Number" value="<?php echo $profile['phone_no']; ?>" /></div>
<li><?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?></li>
</ul>
<?php echo validation_errors();?>
<?php echo form_close(); ?>
<?php
}
?>
Controller Profile.php
public function update_profile(){
$email = $_SESSION['email'];
// $data['profile'] = $this->profile_model->getprofile($email);
$data = array(
'password' => $this->input->post('pass'),
'con_password' => $this->input->post('con_pass'),
'phone_no' => $this->input->post('phone_no')
);
print_r($data);
if($this->profile_model->updateprofile($email,$data))
{
$this->load->view('provider/profile', $data);
}
}
Model profile_model.php
public function updateprofile($email, $data){
$this->db->where('email', $email);
return $this->db->update('user', $data);
}
}
Try like below with form validation
https://www.codeigniter.com/user_guide/libraries/form_validation.html
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
EXAMPLE
public function update_profile() {
$this->load->library('form_validation');
// You can change what you want set for the rules your self this just example:
$this->form_validation->set_rules('pass', 'pass', 'trim|required');
$this->form_validation->set_rules('con_pass', 'con_pass', 'trim|required|matches[pass]');
$this->form_validation->set_rules('phone_no', 'phone_no', 'trim|required');
if ($this->form_validation->run() == TRUE) {
// Update model stuff
}
$email = $_SESSION['email']; // User id instead of email.
$profile_data = $this->users_model->getprofile($email);
if ($this->input->post('pass')) {
$data['pass'] = $this->input->post('pass');
} elseif (!empty($profile_data)) {
$data['pass'] = $profile_data['pass'];
} else {
$data['pass'] = '';
}
if ($this->input->post('con_pass')) {
$data['con_pass'] = $this->input->post('con_pass');
} elseif (!empty($profile_data)) {
$data['con_pass'] = $profile_data['con_pass'];
} else {
$data['con_pass'] = '';
}
if ($this->input->post('phone_no')) {
$data['phone_no'] = $this->input->post('phone_no');
} elseif (!empty($profile_data)) {
$data['phone_no'] = $profile_data['phone_no'];
} else {
$data['phone_no'] = '';
}
$this->load->view('provider/profile', $data);
}
Model function
public function getprofile($email) {
$this->db->where('email', $email);
$query = $this->db->get('users');
return $query->row_array();
}
View Example
<?php echo form_open('profile/update_profile'); ?>
<?php echo validation_errors();?>
<input type="password" name="pass" value="<?php echo set_value('pass', $pass);?>"/>
<input type="password" name="con_pass" value="<?php echo set_value('con_pass', $con_pass);?>"/>
<input type="text" name="phone_no" value="<?php echo set_value('phone_no', $phone_no);?>" />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?>
<?php echo form_close();?>

CodeIgniter form validation not showing due to redirect

I have this edit page that has gets its id and status from uri segments. The problem is that if the user doesn't select an image or complete a part of the form, the page is supposed to reload and show the validation errors for the form. However that page reload causes the data in the form to go missing. Is there a way to solve this issue? Any help would be greatly appreciated. I attached my view, and controller
View
<?php if($edit == "false"){
echo form_open_multipart('Control/Products/ProductDetail/addProduct','class="productdetail"');
}else{
echo form_open_multipart('Control/Products/ProductDetail/editProduct','class="productdetail"');
}?>
<label for="inputproductname">Product Name</label>
<input type="text" class="form-control" id="inputproductname" name="inputproductname" placeholder="Name" value="<?php echo $name; ?>">
<label for="inputproductdescription">Product Description</label>
<textarea class="form-control" id="inputproductdescription" name="inputproductdescription" placeholder="Description" rows="7"
><?php echo $description; ?></textarea>
<label for="inputproductprice">Product Price</label>
<input type="price" class="form-control" id="inputproductprice" name="inputproductprice" placeholder="Price" value="<?php echo $price; ?>">
<label for="inputproductimage">Product Image</label>
<p><input type="file" class="form-control-file" name="upload" id="upload" aria-describedby="fileHelp"></p>
<input type="hidden" class="form-control" id="inputcurrentid" name="inputcurrentid" value="<?php echo $currentid; ?>">
<input type="hidden" class="form-control" id="inputcurrentstatus" name="inputcurrentstatus" value="<?php echo $currentstatus; ?>">
<button type="submit" class="btn btn-primary">
<?php if($edit == "false"){
echo "Add";
}else{
echo "Edit";
}?>
</button>
Cancel
<?php echo form_close(); ?>
<?php echo validation_errors(); ?>
<p><?php echo $this->session->flashdata('Form'); ?></p>
Controller
public function index(){
$productid = $this->uri->segment(5);
$editstatus = $this->uri->segment(6);
if($editstatus == "false"){
$data['name'] = '';
$data['description'] = '';
$data['price'] = '';
$data['edit'] = "false";
$data['message']='';
$data['currentid'] = '';
$data['currentstatus'] = '';
}else{
$product = $this->ProductsModel->getProduct($productid);
foreach ($product as $productdetail){
$data['name'] = $productdetail->name;
$data['description'] = $productdetail->description;
$data['price'] = $productdetail->price;
}
$data['edit'] = "true";
$data['message']='';
$data['currentid'] = $productid;
$data['currentstatus'] = $editstatus;
}
$this->load->view('control/controlMenu/navigationLink');
$this->load->view('control/controlProducts/productDetail',$data);
$this->load->view('control/controlMenu/navigationJquery');
}
public function editProduct(){
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
$this->form_validation->set_rules('inputproductname', 'Name', 'trim|required');
$this->form_validation->set_rules('inputproductdescription', 'Description', 'trim|required');
$this->form_validation->set_rules('inputproductprice', 'Price', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('upload', 'Image', 'required');
}
$inputproductname = $this->input->post('inputproductname');
$inputproductdescription = $this->input->post('inputproductdescription');
$inputproductprice = $this->input->post('inputproductprice');
$inputdateadded = date('Y-m-d');
$inputcurrentid = $this->input->post('inputcurrentid');
$inputcurrentstatus = $this->input->post('inputcurrentstatus');
$config['upload_path'] = $this->getProductImageFolderPath();
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 3000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $inputproductname;
$this->load->library('upload', $config);
if($this->form_validation->run()==false){
redirect('/Control/Products/ProductDetail/index/'.$inputcurrentid.'/'.$inputcurrentstatus);
}else{
if(!$this->upload->do_upload('upload')){
$this->session->set_flashdata('Form',$this->upload->display_errors());
redirect('Control/'.$this->getCurrentModule().'/'.$this->getClassName());
}else{
$extension = $this->upload->data('file_ext');
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice,
'imagePath'=>$config['upload_path'].$config['file_name'].$extension,
'dateAdded'=>$inputdateadded
);
$this->db->trans_start();
$this->ProductsModel->editProduct($productid,$productdetails);
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products/Products');
}
}
}
}
if($this->form_validation->run()==false){
redirect('/Control/Products/ProductDetail/index/'.$inputcurrentid.'/'.$inputcurrentstatus);
I think the problem with this redirect stmt don't use it instead you need to use load view so that it will preserves the errors array.
just do ths in your controller
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('field', form_error('field', '<span class="text-danger pl-3">', '</span>'));
redirect("url");
} else {
# code...
}
and in your redirect page use
<?= $this->session->flashdata('field'); ?>

Ion Auth Flashdata Check Not Working

I am using Ben Edmunds Ion Auth Library.
I am having a problem with any function that uses the csrf_nonce methods - it is failing the check on post.
I have checked that the flashdata is getting set (I can see it in the form as a hidden input [edit_user for example]), but when you submit the form the flashdata check is failing.
I am using the database for the session if that makes any difference.
Code snippets;
Controller
function edit_user($id) {
$this->data['title'] = "Edit User";
if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) {
redirect('auth', 'refresh');
} //!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()
$user = $this->ion_auth->user($id)->row();
$groups = $this->ion_auth->groups()->result_array();
$currentGroups = $this->ion_auth->get_users_groups($id)->result();
//process the phone number
if (isset($user->phone) && !empty($user->phone)) {
$user->phone = explode('-', $user->phone);
} //isset($user->phone) && !empty($user->phone)
//validate form input
$this->form_validation->set_rules('first_name', $this->lang->line('edit_user_validation_fname_label'), 'required|xss_clean');
$this->form_validation->set_rules('last_name', $this->lang->line('edit_user_validation_lname_label'), 'required|xss_clean');
$this->form_validation->set_rules('email', $this->lang->line('create_user_validation_email_label'), 'required|valid_email');
$this->form_validation->set_rules('company', $this->lang->line('edit_user_validation_company_label'), 'required|xss_clean');
$this->form_validation->set_rules('groups', $this->lang->line('edit_user_validation_groups_label'), 'xss_clean');
if (isset($_POST) && !empty($_POST)) {
// do we have a valid request?
if ($id != $this->input->post('id')) {
show_error($this->lang->line('error_csrf'));
} //$this->_valid_csrf_nonce() === FALSE || $id != $this->input->post('id')
$data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'company' => $this->input->post('company'),
'email' => $this->input->post('email')
);
//Update the groups user belongs to
$groupData = $this->input->post('groups');
if (isset($groupData) && !empty($groupData)) {
$this->ion_auth->remove_from_group('', $id);
foreach ($groupData as $grp) {
$this->ion_auth->add_to_group($grp, $id);
} //$groupData as $grp
} //isset($groupData) && !empty($groupData)
//update the password if it was posted
if ($this->input->post('password')) {
$this->form_validation->set_rules('password', $this->lang->line('edit_user_validation_password_label'), 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
$this->form_validation->set_rules('password_confirm', $this->lang->line('edit_user_validation_password_confirm_label'), 'required');
$data['password'] = $this->input->post('password');
} //$this->input->post('password')
if ($this->form_validation->run() === TRUE) {
$check = $this->ion_auth->update($user->id, $data);
if (FALSE == $check) {
$this->session->set_flashdata('message', $this->ion_auth->errors());
redirect("auth/edit-user/$id", 'refresh');
} else {
//check to see if we are creating the user
//redirect them back to the admin page
$this->session->set_flashdata('message', "User Saved");
redirect("auth/users", 'refresh');
}
} //$this->form_validation->run() === TRUE
} //isset($_POST) && !empty($_POST)
//display the edit user form
$this->data['csrf'] = $this->_get_csrf_nonce();
//set the flash data error message if there is one
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
//pass the user to the view
$this->data['user'] = $user;
$this->data['groups'] = $groups;
$this->data['currentGroups'] = $currentGroups;
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'value' => $this->form_validation->set_value('first_name', $user->first_name)
);
$this->data['last_name'] = array(
'name' => 'last_name',
'id' => 'last_name',
'type' => 'text',
'value' => $this->form_validation->set_value('last_name', $user->last_name)
);
$this->data['company'] = array(
'name' => 'company',
'id' => 'company',
'type' => 'text',
'value' => $this->form_validation->set_value('company', $user->company)
);
$this->data['email'] = array(
'name' => 'email',
'id' => 'email',
'type' => 'email',
'value' => $this->form_validation->set_value('email', $user->email)
);
$this->data['password'] = array(
'name' => 'password',
'id' => 'password',
'type' => 'password'
);
$this->data['password_confirm'] = array(
'name' => 'password_confirm',
'id' => 'password_confirm',
'type' => 'password'
);
$this->_render_page('auth/admin/users/update', $this->data);
}
function _get_csrf_nonce() {
$this->load->helper('string');
$key = random_string('alnum', 8);
$value = random_string('alnum', 20);
$this->session->set_flashdata('csrfkey', $key);
$this->session->set_flashdata('csrfvalue', $value);
return array(
$key => $value
);
}
function _valid_csrf_nonce() {
if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')) {
return TRUE;
} //$this->input->post($this->session->flashdata('csrfkey')) !== FALSE && $this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue')
else {
return FALSE;
}
}
View;
<h1><?php echo lang('edit_user_heading');?></h1>
<p><?php echo lang('edit_user_subheading');?></p>
<!--<div id="infoMessage" class="info"><?php echo $message;?></div>-->
<?php
if (isset($message)) {
?>
<div id="infoMessage" class="alert alert-info">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4>Message</h4>
<?php echo $message;?>
</div>
<?php
}
?>
<?php echo form_open(uri_string(), 'class="form-horizontal"'); ?>
<div class="control-group <?php echo form_error_class('first_name') ?>">
<label class="control-label" for="first_name">
<?php echo lang('edit_user_fname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="first_name"
name="first_name"
placeholder="<?php echo lang('edit_user_fname_label'); ?>"
value="<?php echo set_value('first_name', $first_name['value']); ?>"
class="error"/>
<?php echo form_error('first_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('last_name') ?>">
<label class="control-label" for="last_name">
<?php echo lang('edit_user_lname_label'); ?>
</label>
<div class="controls">
<input type="text"
id="last_name"
name="last_name"
placeholder="<?php echo lang('edit_user_lname_label'); ?>"
value="<?php echo set_value('last_name', $last_name['value']); ?>"
class="error"/>
<?php echo form_error('last_name'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('company') ?>">
<label class="control-label" for="company">
<?php echo lang('edit_user_company_label'); ?>
</label>
<div class="controls">
<input type="text"
id="company"
name="company"
placeholder="<?php echo lang('edit_user_company_label'); ?>"
value="<?php echo set_value('company', $company['value']); ?>"
class="error"/>
<?php echo form_error('company'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('email') ?>">
<label class="control-label" for="email">
<?php echo lang('edit_user_email_label'); ?>
</label>
<div class="controls">
<input type="text"
id="email"
name="email"
placeholder="<?php echo lang('edit_user_email_label'); ?>"
value="<?php echo set_value('email', $email['value']); ?>"
class="error"/>
<?php echo form_error('email'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password') ?>">
<label class="control-label" for="password">
<?php echo lang('edit_user_password_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password"
name="password"
placeholder="<?php echo lang('edit_user_password_label'); ?>"
value="<?php echo set_value('password'); ?>"
class="error"/>
<?php echo form_error('password'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('password_confirm') ?>">
<label class="control-label" for="password_confirm">
<?php echo lang('edit_user_password_confirm_label'); ?>
</label>
<div class="controls">
<input type="password"
id="password_confirm"
name="password_confirm"
placeholder="<?php echo lang('edit_user_password_confirm_label'); ?>"
value=""
class="error"/>
<?php echo form_error('password_confirm'); ?>
</div>
</div>
<div class="control-group <?php echo form_error_class('groups') ?>">
<div class="controls <?php echo form_error_class('groups') ?>">
<h3><?php echo lang('edit_user_groups_heading');?></h3>
<?php
foreach ($groups as $group) {
?>
<label class="checkbox">
<?php
$gID=$group['id'];
$checked = null;
$item = null;
foreach($currentGroups as $grp) {
if ($gID == $grp->id) {
$checked= ' checked="checked"';
break;
}
}
?>
<input type="checkbox" name="groups[]" value="<?php echo $group['id'];?>"<?php echo $checked;?>>
<?php echo $group['name'];?>
</label>
<?php
}
?>
</div>
</div>
<?php echo form_hidden('id', $user->id);?>
<?php echo form_hidden($csrf); ?>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" value="<?php echo lang('edit_user_submit_btn'); ?>" />
</div>
</div>
<?php echo form_close();?>
First check
$this->session->set_flashdata('message',
$this->ion_auth->errors()
);
having set value
I have found the solution (or this fix works just for me).
I changed the session driver in the config to use native sessions from cookie.
Line 284 of config.php => $config['sess_driver'] = 'native';
Golden rule: never trust CI sessions!
Some notions about FLASHDATA
CSRF and Flashdata:
FLASHDATA will only be available for the NEXT server request, and are then automatically cleared!
e.g.:
AJAX calls function_1, which sends CSRF key/value back to function_1_success
function_1_success sets hidden input fields for CSFR key and value
and enables function_2, which compares POST variables with flashdata
this is how it works (with or without AJAX, that was just an example).
How it doesn't work: if you create a php function which does
$this->session->set_flashdata('item', 'value') and then try to read with echo $this->session->flashdata('item') you will get an empty string, only after a refresh of this function,your flashdata values show

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