0

I'm trying to prevent a method from executing if validation in constructor fails. I'm using AJAX and I'm sending the request to a url like example/search. I'm currently checking if a variable isn't false but I think there's a better way of doing that, isn't there?

class Example extends CI_Controller {

        public $error;
        function __construct() {
            parent::__construct();
                    //validation rules    
            if($this->form_validation->run() == FALSE) {
                $this->error=1;
            }

        }
        function search() {
            if(!$this->error) {
            //code
            }
        }
    }
4

1 回答 1

0

应用程序/配置/form_validation.php

$config = array(
     'search' => array(
        array('field'=>'', 'label'=>'', 'rules'=>''),
        array('field'=>'', 'label'=>'', 'rules'=>'')
     ),
);

-

控制器

public function search(){

   //is ajax request?
   if( !$this->input->is_ajax_request() )
   {
      return show_error('Bad Request!'); // bye bye, stop execution
   }

   $this->output->set_status_header('200');

   if( ! $this->form_validation->run('search') )
   {
      echo json_encode(array(
          'error' => 1,
          'errors' => array(
                'field' => form_error('field')
           )
      ));
      return; // bye bye, stop execution
   }

   //all good, continue executing
   //.....
}

编辑

//For just a constructor 

protected $isValidated = TRUE;

public function __construct(){

    //check for valid ajax request
    //do this in parent class(ajax_controller) ?

    if( !$this->form_validation->run('search') )
    {
       $this->isValidated = FALSE;
       return echo json_encode( array('error' => 1));
    }

    if($isValidated)
    {
         $this->_search( $this->input->post() );
    }
}

protected function _search( $input ){}

-

class Ajax_Controller extends CI_Controller{
    public function __construct(){
       if( !$this->input->is_ajax_request() )
       {
          return show_error('Bad Request!');
       }

       $this->output->set_status_header('200');
    }
}
于 2013-02-18T13:37:27.973 回答