开发者

Codeigniter using flashdata and form_validation

I am trying to learn PHP with codeigniter, had have come across a problem. Am writing a user registration form with form validation. If the user input has passed validation, it will check database if the email is already existing in the database. If it exists, it should show an error to the user. I am storing this error in the flashdata session variable, and redirecting the user to the registration form. But after redirection, the form set_values are empty. I wan开发者_运维问答t it to be populated with the values the user already filled out earlier. If I use $this->load->view('registration_form').. the field values are populated like I want, but the database error does not show, since it's not a new server call.

Does the form_validation values (set_value()) disappear on a redirect? If it does, how can I prepopulate the field values?


If you redirect when a form that posts to itself is valid, then yes you will lose set_value() as there is now nothing in the $_POST array - this is why you redirect, so a user won't resubmit the form on refresh.

What you should do is create your own validation rule in a callback function in the same controller. See here http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks

What you need to do is pass the email to a model in the callback that will check the email against your database and return false if it is already there. This way, your form will not be valid and not redirect if the email already exists.


I was just adding a form to an old CI installation minutes ago and had this issue. It's funny you should mention it.

Since set_value() and the related functions are only reading the $_POST data, they will not hold the value after a refresh. You have a few options:

  1. Don't redirect until the form is valid.
  2. Assign the $_POST array to a flashdata (session) variable, and copy it to the $_POST array manually after the redirect
  3. Write your own group of functions to handle this with either flashdata or session data or other method, and don't use the set_value() functions.

For the quickest fix, use #1. I don't like manually setting $_POST values, so I don't really endorse #2, but it should work. For the long term - use #3. I find that the CI form handling is often lacking, and my personal form interaction code base has grown quite a bit over time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜