Codeigniter回调下拉表单验证

时间:2014-02-22 06:56:04

标签: codeigniter

在将所选国家/地区添加到数据库之前,只想验证我的codeigniter下拉表单。问题是它插入了默认值" selectcountry'进入数据库而不是显示消息"请选择您所在的国家/地区。"请帮帮我:)。

这是我的模特:

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

class Model_example extends CI_Model {

  function __construct()
 {
  //Call the Model constructor
   parent::__construct();
 }

public function did_add() {

        $data = array(
        'country' => $this->input->post('country')                 
                     );     
        $query = $this->db->insert('example_table', $data);

        if ($query) {
            return true;} 
        else {
            return false;}      
    }  
}

以下是我的观点:

     $this->load->helper("form","file","html","url");    


     echo $message;

     echo validation_errors();

     echo form_open("example/add");

     echo form_label("Country:<br>","country");
     $data = array(
          "selectcountry"  => "Select Country",               
          "CA" => "Canada",
          "US" => "United States",
          "ZW" => "Zimbabwe"
                  );
     echo form_dropdown('country', $data, 'selectcountry');
     echo br(1);


     echo form_submit("Submit", "Add");

     echo form_close();

这是我的控制器:

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

class Example extends MX_Controller {

    public function index() {       
            $data["message"] = "";            
            $this->load->view("view_example",$data);        
               }

    public function add() {                     
            $this->load->library('form_validation');
            $this->load->model('model_example');            
            $this->form_validation->set_rules('country', 'Country', 'required|callback_country_check');     
            if($this->form_validation->run()){
            $this->model_example->did_add();    
            }
            else {
            $data["message"] = "";          
            $this->load->view("view_example",$data);               
            }       
           }

     public function country_check()
    {
            if ($this->input->post('country') === 'selectcountry')  {
            $this->form_validation->set_message('country_check', 'Please choose your country.');
            return FALSE;
        }
        else {
            return TRUE;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在您的视图页面中更改此行

$data = array(
          "selectcountry"  => "Select Country",               
          "CA" => "Canada",
          "US" => "United States",
          "ZW" => "Zimbabwe"
                  );
  echo form_dropdown('country', $data, 'selectcountry');

到这个

$data = array(
          ""  => "Select Country",               
          "CA" => "Canada",
          "US" => "United States",
          "ZW" => "Zimbabwe"
                  );
  echo form_dropdown('country', $data, set_value('country'));

您不需要另一个回调函数来检查值是否为空。