Welcome Guest, Not a member yet? Register   Sign In
same rule for is_unique when editing and adding entries
#1

[eluser]keithics[/eluser]
Hi guys,

I hope this will help you.

Problem:
When adding a new entry with is_unique will work just fine but what about when you want to update the entry using the same form validation rule? is_unique will not work because it will detect that you are adding a duplicate entry. Which sucks, and you will be forced to create a new rule just for that.


Prerequisites:
1. when editing, you must pass the primary key as post data (which we mostly do)
Example where user_id is the primary key:
Code:
<input type="hidden" value="1" name="user_id" />

Benefits:
1. Same form validation rule for editing and adding

Code:
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class My_Form_validation extends CI_Form_validation {

public function is_unique($str, $field)
{
  list($table, $field)=explode('.', $field);
  $q = $this->CI->db->query("SHOW KEYS FROM $table WHERE Key_name = 'PRIMARY'")->row();
  $primary_key = $q->Column_name;
  
  if($this->CI->input->post($primary_key) > 0):
   $query = $this->CI->db->limit(1)->get_where($table, array($field => $str,$primary_key.' !='=>$this->CI->input->post($primary_key)));
  else:
   $query = $this->CI->db->limit(1)->get_where($table, array($field => $str));
  endif;
  
  return $query->num_rows() === 0;
    }
}


/* End of file My_Form_validation.php */
/* Location: ./application/libraries/My_Form_validation.php */


Messages In This Thread
same rule for is_unique when editing and adding entries - by El Forum - 02-22-2012, 03:14 AM
same rule for is_unique when editing and adding entries - by El Forum - 02-22-2012, 10:35 AM
same rule for is_unique when editing and adding entries - by El Forum - 02-22-2012, 06:11 PM
same rule for is_unique when editing and adding entries - by El Forum - 05-04-2012, 07:20 AM
same rule for is_unique when editing and adding entries - by El Forum - 09-30-2012, 04:10 PM
same rule for is_unique when editing and adding entries - by El Forum - 09-30-2012, 05:42 PM



Theme © iAndrew 2016 - Forum software by © MyBB