Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a post-method form to same get-url in different function in CodeIgniter?

I found CodeIgniter form validation to show error message with load->view method, and will lost field error message if use "redirect".

Currently I use one function to show form page, and another function to deal form post.

class Users extends CI_Controller {
  function __construct() {
      parent::__construct();
  }

  public function sign_up()
  {
    $this->load->view('users/sign_up');
  }

public function do_sign_up(){
      $this->form_validation->set_rules('user_login', 'User Name', 'trim|required|is_unique[users.login]');
      $this->form_validation->set_rules('user_email', 'Email', 'trim|required|valid_email|is_unique[users.email]');

      if ($this->form_validation->run() == FALSE) {
          $this->load->view('users/sign_up');
      }else {
       // save post user data to users table
       redirect_to("users/sign_in");
}


When form validation failed, url in browser will changed to "/users/do_sign_up", I want to keep same url in sign_up page.

Use redirect("users/sign_up") method in form validation failed will keep same url, but validation error message will lost.

in Rails, I cant use routes to config like this:

get "users/sign_up"       => "users#signup"
post "users/sign_up"       => "users#do_signup"
like image 409
qichunren Avatar asked Oct 08 '22 15:10

qichunren


1 Answers

imho it's not necessary to check the request method because if the user 'GET' to the page you want to show the sign up view... if they user 'POST' to the page and fails validation you ALSO want to show the sign up view. You only won't want to show the sign up view when the user 'POST' to the page and passes validation.

imho here's the most elegant way to do it in CodeIgniter:

public function sign_up()
{
    // Setup form validation
    $this->form_validation->set_rules(array(
        //...do stuff...
    ));

    // Run form validation
    if ($this->form_validation->run()) 
    {
        //...do stuff...
        redirect('');
    }

    // Load view
    $this->load->view('sign_up');
}

Btw this is what im doing inside my config/routes.php to make my CI become RoR-like. Remember that your routes.php is just a normal php file so u can put a switch to generate different routes depending on the request method.

switch ($_SERVER['REQUEST_METHOD'])
{
    case 'GET':
        $route['users/sign_up'] = "users/signup";
    break;
    case 'POST':
        $route['users/sign_up'] = "users/do_signup";
    break;
}
like image 89
PK. Avatar answered Oct 12 '22 12:10

PK.