Unique field in codeigniter - php

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

Related

codeigniter how to submit multiple rows with the same name

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

Codeigniter validation errors are not displaying

My codeigniter validation errors are not displaying someone can help?
my code is
public function addProduct(){
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
if (!$this->form_validation->run() == FALSE)
{
// some stuff on validation success
}
else{
$this->load->view('product/addProduct');
}
}
and i have added
echo validation_errors(); in my view and action of the form is product/addProduct.
Try this it's work for you.
form_error() function return your form error.
$post_fields = $this->input->post();
$data['msg'] = '<ul>';
foreach ($post_fields as $k => $v) {
if (form_error($k))
$data['msg'] .= "<li>" . strip_tags(form_error($k)) . "</li>\n";
}
$data['msg'].='</ul>';
$this->load->view('product/addProduct',$data);
OR
echo validation_errors();//this function also return form error.
On view example
<?php echo validation_errors('<div class="error">', '</div>'); ?>
<!-- lower case for the controller name on form open -->
<?php echo form_open_multipart('product/addProduct');?>
<h5>productName</h5>
<input type="text" name="productName" value="<?php echo set_value('productName'); ?>" size="50" />
<h5>productPrice</h5>
<input type="text" name="productPrice" value="<?php echo set_value('productPrice'); ?>" size="50" />
<div><input type="submit" value="Submit" /></div>
<?php echo form_close();?>
Controller
Make sure your file name and class name is something like this below where first letter only upper case
Guide
Filename: Product.php
<?php
class Product extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->helper('url');
}
public function addProduct(){
// You can get data from here also
$this->data['some'] = 'Blah';
$this->form_validation->set_rules('productName', 'Product Name', 'required|trim');
$this->form_validation->set_rules('productPrice', 'Product Price', 'required|trim');
// remove your !
if ($this->form_validation->run() == FALSE){
// You can just display view in this area you do not have to load it multiple times
$this->load->view('header', $this->data);
$this->load->view('product/addProduct');
$this->load->view('footer');
} else {
// some stuff on validation success
}
}
}
Also check you have set your base url in config.php is required now in CI3 versions.

Codelgniter Form Validation Showed double repeated form after validate

Tried to read though all the webpages and docs in google and stack flow but still could not solve the problem.
I tried to do a simple data validation for registration form and it turns out showing another form below the original one after I press submit to show the error messages with a new form.
I am a newbie in this language so please let me know if I attache not enough codes or information.
Controller account:
<?php
class Account extends MY_Controller {
public function __construct() {
parent::__construct();
session_start();
$this->load->model('user');
$this->load->helper(array('form','url','html'));
$this->load->library('session');
$this->load->library('form_validation');
}
public function registration() {
$data = $this->user->users_info();
$this->load->view('account/registration',$data);
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password ', 'required|matches[passconf]|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if($this->input->post('submit')) {
$username= $this->input->post('username');
$email= $this->input->post('email');
$query_u= $this->user->retrieve_by_username($username);
$query_e= $this->user->retrieve_by_email($email);
if ($this->form_validation->run() == FALSE){
$this->load->view('account/registration',$data); ←---------------- (I think this is wrong, it makes load the second form out.)
}
else{
if(!empty($query_u) or !empty($query_e)) {
redirect('account/registrat');
}
else {
$data = array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>$this->input->post('password'),
'is_admin'=>0,
);
$this->user->create_user($data);
redirect('/account/login');
}
}
}
}
View Registration.php
<center>
<?php echo form_open_multipart('account/registration'); ?>
<h5><?php echo $b_username;?> (Minimum 5 characters)</h5>
<input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" size="50" /><?php echo form_error('username'); ?>
<h5><?php echo $b_email;?></h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<?php echo form_error('email'); ?>
<h5><?php echo $b_password;?> (Minimum 5 characters)</h5>
<input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" />
<?php echo form_error('password'); ?>
<h5><?php echo $b_passconf;?></h5>
<input type="text" name="passconf" value="" size="50" />
<?php echo form_error('passconf'); ?>
<h5></h5>
<div><?php echo form_submit('submit', 'Submit') ?></div>
</center>
Model user.php
<?php
class User extends CI_Model {
function __construct() {
parent::__construct();
$this->load->database();
}
function users_info() {
$data['b_id'] = 'id';
$data['b_username'] = 'Username';
$data['b_email'] = 'Email';
$data['b_password'] = 'Password';
$data['b_passconf'] = 'Enter Password Again';
$data['b_is_admin'] = 'Is_admin';
$data['b_default_privacy'] = 'Default_privacy';
$data['b_first_name'] = 'First_Name';
$data['b_last_name'] = 'Last_Name';
$data['b_gender'] = 'Gender';
$data['b_birthday'] = 'Birthday';
$data['b_friend_id'] = 'Friend_id';
$data['b_weight'] = 'Weight';
$data['b_height'] = 'Height';
$data['b_daily_cal_intake'] = 'Daily_calorie_intake';
$data['b_target_weight'] = 'Target_weight';
$data['b_regional_id'] = 'Region';
$data['b_profile_pic'] = 'Profile Picture';
return $data;
}
function retrieve_by_username($username) {
$query = $this->db->get_where('001_users',array('username'=>$username));
return $query->row_array();
}
function retrieve_by_email($email) {
$query = $this->db->get_where('001_users', array('email'=>$email));
return $query->row_array();
}
Change your function to this and try..
public function registration()
{
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[20]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('password', 'Password ', 'required|matches[passconf]|min_length[5]');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
if ($this->form_validation->run() == false) // if validation fails for first time and every time when ever condtion is not satisified
{
$data = $this->user->users_info();
$this->load->view('account/registration',$data);
}
else
{
$username= $this->input->post('username');
$email= $this->input->post('email');
$query_u= $this->user->retrieve_by_username($username);
$query_e= $this->user->retrieve_by_email($email);
if(!empty($query_u) or !empty($query_e)) {
redirect('account/registrat');
}
else {
$data = array(
'username'=>$this->input->post('username'),
'email'=>$this->input->post('email'),
'password'=>$this->input->post('password'),
'is_admin'=>0
);
$this->user->create_user($data);
// send sucess msg here
redirect('/account/login');
}
}
}

Codeigniter validation is not working

I am new in codeigniter .I have done validation for my project .But it is not working fine .I have written my all code here .First is view page and second is my controller page.Please help anyone
<?php $this->load->helper('form');
echo validation_errors();
echo form_open('SM_in_controller/sm_login_action');
?>
<input class="login_input" type="text" placeholder="Username" name="username" id="username"/>
<input type="submit" value="Login" class="login_button" id="login_button"/>
</form>
and my controller
public function sm_login_action() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
}
In your controller, when you call the "run" method is when the proccess is done:
public function sm_login_action() {
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
if( $this->form_validation->run() ) { // Return TRUE on success
// Success
} else {
// Failure
}
}
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('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;
}
}
}
?>
try this for more details.
https://www.codeigniter.com/user_guide/libraries/form_validation.html
Try this
<input class="login_input" type="text" placeholder="Username" name="username" id="username" required/>
Hope this helps

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