Codeigniter:在编辑时验证表单字段

时间:2014-03-10 06:48:49

标签: php codeigniter

我遇到了麻烦,并且一周多以来一直试图找到一个解决方案来禁止重复的表单内容(如果它已经存在于数据库中)。

因此它将检查除了id(行)当前正在编辑的所有行,如果存在相同的值,则应该给出错误消息。

这是我的代码。

位置控制器

public function position_edit($id = NULL)
{

    $this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');

    $this->data['position'] = $this->positions_model->get($id);
    count($this->data['position']) || $this->data['errors'][] = 'position could not be found';

    $id = $this->uri->segment(4);
    $this->db->where('position', $this->input->post('position'));
    !$id || $this->db->where('id !=', $id);
    $pos = $this->positions_model->get();

    echo '<pre>', print_r($pos), '</pre>';

    if (count($pos) > 0) {
        $this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');            
        $this->form_validation->set_message('is_unique', lang('error_position_exists'));
    }

    if ($this->form_validation->run() === TRUE) {
        $data = $this->positions_model->array_from_post(array('position', 'label'));
        $this->positions_model->save($data, $id);
        $this->session->set_flashdata('message', lang('position_record_updated'));
        $this->data['message'] = $this->session->flashdata('message');
        $this->session->set_flashdata('message_type', 'success');
        $this->data['message_type'] = $this->session->flashdata('message_type');

        //redirect('admin/hr/positions', 'refresh');
    }

    // Load the view            
    $this->load->view('hr/positions/edit', $this->data);
}

位置模型

class Positions_Model extends MY_Model
{

    protected $_table_name      =   'positions';
    protected $_order_by        =   'label ASC';

    // This $rules currently not in use since it has been
    // set directly to the controller edit method code
    public $rules               =   array(        
        'position' => array(
                'field' => 'position',
                'label' => 'Position Code',
                'rules' => 'trim|required|max_length[10]|xss_clean'
            ),
        'label' => array(
                'field' => 'label',
                'label' => 'Position Label',
                'rules' => 'trim|required|max_length[50]|xss_clean'
            ),                                               

        );


    public function get_new()
    {
        $position = new stdClass();
        $position->position = '';
        $position->label = '';
        return $position;
    }


    public function get_positions($id = NULL, $single = FALSE)
    {
        $this->db->get($this->_table_name);        
        return parent::get($id, $single);
    }


    public function get_positions_array($id = NULL, $single = FALSE)
    {

        $this->db->get($this->_table_name);        
        $positions = parent::get($id, $single);

        $array = array();
        foreach($positions as $pos){
            $array[] = get_object_vars($pos);
        }

        return $array;
    }

    public function delete($id)
    {
        // Delete a position
        parent::delete($id);

    }        

}

数据库模型

class MY_Model extends CI_Model 
{

    protected $_table_name      =   '';
    protected $_primary_key     =   'id';
    protected $_primary_filter  =   'intval';
    protected $_order_by        =   '';
    public    $rules            =   array();
    protected $_timestamps      =   FALSE;

    function __construct()
    {
        parent::__construct();
    }


    public function array_from_post($fields)
    {
        $data = array();

        foreach ($fields as $field) {
            $data[$field] = $this->input->post($field);
        }
        return $data;
    }


    public function get($id = NULL, $single = FALSE)
    {
        if($id != NULL) {
            $filter = $this->_primary_filter;
            $id = $filter($id);
            $this->db->where($this->_primary_key, $id);
            $method = 'row';
        } elseif($single == TRUE) {
            $method = 'row';
        } else {
            $method = 'result';
        }

        if(!count($this->db->ar_orderby)) {
            $this->db->Order_by($this->_order_by);
        }

        return $this->db->get($this->_table_name)->$method();
    }


    public function get_by($where, $single = FALSE)
    {
        $this->db->where($where);
        return $this->get(NULL, $single);
    }


    public function save($data, $id = NULL)
    {
        // Set timestamps
        if ($this->_timestamps == TRUE) {
            $now = date('Y-m-d H:i:s');
            $id || $data['created'] = $now;
            $data['modified'] = $now;
        }

        // Insert
        if ($id === NULL) {
            !isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
            $this->db->set($data);
            $this->db->insert($this->_table_name);
            $id = $this->db->insert_id();            
        } else {
        // Update
            $filter = $this->_primary_filter;
            $id = $filter($id);
            $this->db->set($data);
            $this->db->where($this->_primary_key, $id);
            $this->db->update($this->_table_name);    
        }

        return $id;                

    }


    public function delete($id)
    {
        $filter = $this->_primary_filter;
        $id = $filter($id);

        if (!$id) {
            return FALSE;
        }

        $this->db->where($this->_primary_key, $id);
        $this->db->limit(1);
        $this->db->delete($this->_table_name);
    }


}

我也尝试了回调函数,但它根本无法正常工作,无法找到导致问题的原因。


修改
请注意 如果我插入已经存在但未验证的值并且如果该行不存在则存储数据

上面的代码正在给出消息>

更新

if ($this->form_validation->run() === TRUE) {

    //print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));

    if($this->positions_model->unique_value('position', $this->uri->segment(4))) {                
        $this->form_validation->set_message('unique_value', lang('error_position_exists'));
    } else {

        $data = $this->positions_model->array_from_post(array('position', 'label'));
        $this->positions_model->save($data, $id);
        $this->session->set_flashdata('message', lang('position_record_updated'));
        $this->data['message'] = $this->session->flashdata('message');
        $this->session->set_flashdata('message_type', 'success');
        $this->data['message_type'] = $this->session->flashdata('message_type');

        redirect('admin/hr/positions', 'refresh');
    }
}

在控制器中

public function unique_value($field, $id)
{
    $id = $this->uri->segment(4);
    $this->db->where($field, $this->input->post($field));
    !$id || $this->db->where('id !=', $id);
    $position = $this->positions_model->get();

    if (count($position)) {
        return TRUE;
    }

    return FALSE;
}

2 个答案:

答案 0 :(得分:0)

请注意:我不知道您的代码究竟发生了什么,但我不会在插入或更新到模型之间进行检查,只需在控制器中

我会使用checkExist Model函数来解决它,它将检查您要检查的所有值是否存在于DDBB中,并根据它工作。我也会在控制器而不是模型中做到这一点。首先,验证字段,然后检查是否存在除编辑ID之外的值:

$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));

// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {

    if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
        // Insert Value
    } else {
        // Update Value
    }

在您的模型中,您可以通过值存在的位置检查副本:

public function check_duplicate( $values_from_post, $editId ) {

    foreach ( $values_from_post as $key => $value ) {
        $this->db->where( $key, $value );
    }
    $this->db->where('id !=', $editId );

    $result = $this->db->get($this->_table_name);  

    return ( ( $result->num_rows > 0 ) ? true : false );
}

请,我没有检查代码,但这是一个想法,而不是在模型中执行,在控制器中控制它,然后根据发生的情况插入或更新。

答案 1 :(得分:-1)

以下是CodeIgniter的默认validation rule,用于检查两列中的重复条目。

$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');