Codeigniter using flashdata and form_validation - codeigniter

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 want 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:
Don't redirect until the form is valid.
Assign the $_POST array to a flashdata (session) variable, and copy it to the $_POST array manually after the redirect
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.

Related

Using laravels {{old}} on dynamically created inputs

I have a form which allows a user to create an unlimited number of fields. If this forms fails validation I want the user to return to this page with the form populated with their previous input values - i.e. I want these fields to persist.
With a normal form I could do this with {{ old 'title' }}, however, these additional fields are being generated through JavaScript and so I cannot add this PHP snippet. What is the best way for me to retrieve these previous input values?
3 ways to do this, cache, sessions and cookies.
cache and sessions are server side which is much better for security, however it will take extra time and effort for setting up, but if the data is not sensible and can be passed within cookies, better to the cookies.
The best thing about cookies for your current situation is: you can set it up directly from your front end JS code.

Storing multiple CAPTCHA solutions in a session

I'm implementing a 3D CAPTCHA for my website.
My original idea was to store the expected captcha solution in a session variable. After a user submits a form, I'd compare it with their response.
What happens if the user opens my website in multiple tabs though? For each tab a new CAPTCHA challenge is generated and the expected response variable in the session is overwritten.
Now consider the user submits a form in an "old" tab. Since the expected response variable in the session has been overwritten, they won't pass the test.
Should I worry about this? How would you deal with it?
That is the general approach for captchas and sometimes a reason why they do not validate.
This is a goood read http://www.sitepoint.com/captcha-inaccessible-to-everyone/ why not to use captcha
You could however add them in an array instead and see if the answer exists in array.
You are not stating which language you are using otherwise i could provide some code.

Codeigniter - change url at method call

I was wondering if the following can be done in codeigniter.
Let's assume I have a file, called Post.php, used to manage posts in an admin interface.
It has several methods, such as index (lists all posts), add, update, delete...
Now, I access the add method, so that the url becomes
/posts/add
And I add some data. I click "save" to add the new post. It calls the same method with an if statement like "if "this->input->post('addnew')"" is passed, call the model, add it to the database
Here follows the problem:
If everything worked fine, it goes to the index with the list of all posts, and displays a confirmation
BUT
No the url would still be posts/add, since I called the function like $this->index() after verifying data was added. I cannot redirect it to "posts/" since in that case no confirmation message would be shown!
So my question is: can i call a method from anther one in the same class, and have the url set to that method (/posts/index instead of /posts/add)?
It's kinda confusing, but i hope i gave you enough info to spot the problem
Cheers!
Use the redirect() in conjunction with CodeIgniter's Flash Data, or opt for AJAX.

CakePHP Auth Loads Too Many Session Variables

Using CakePHP2.0 Beta I managed to write a custom login handler for my existing database schema. All's well, except that upon logging in I printed out the session variables stored and what Cake's Auth component did is store the entire record from the "Member" table (where my usernames+hashes come from) in session. It is storing an array with data fields that are totally irrelevant to the session. For instance it stores the date the member was created, their address, etc. All pretty useless information for me as I basically only need their ID and maybe username, name, email address.
The offending lines for me are found in: /lib/Cake/Controller/Component/AuthComponent.php line 512. It states,
$this->Session->write(self::$sessionKey, $user);
So my custom authenticate component returns $user and it throws this whole thing into the session. Now, I don't want to go about editing in the core libraries because this project is definitely going to be upgraded when 2.0 comes out. Is there any way to store less information in sessions? I want to keep this whole thing more lightweight.
Possible solution: Change my custom authentication component to only return the fields I need into the $user variable. Are there any concerns about what data I should/shouldn't be returning?
I've solved the problem using my "possible solution". In /app/Controller/Component/auth/MyController.php, I changed the "ClassRegistry::init($userModel)->find" method to have a parameter for 'fields' where I specify only the fields I need. Works like a charm.

Use CodeIgniter form validation in a view

I have footer view that's included on all my pages which contains a form. I would like to be able to make use of CI's form validation library to validate the form. Is that possible?
Currently the form posts back to the current page using the PHP_SELF environment variable. I don't want to get it to post to a controller because when validation fails it loads the controller name in the address bar, which is not the desired behaviour.
Any suggestions gratefully received.
Thanks,
Gaz
One way, whilst far from ideal, would be to create a "contact" function in every controller. This could be in the form of a library/helper.
CI doesn't natively let you call one controller from another, although I believe there are extensions that enable this.
Another option would be an AJAX call instead, which would allow you to post to a generic controller, validate etc whilst remaining on the current page.
In this use case, I would definitely go for an AJAX call to a generic controller. This allows you to show errors even before submitting in the origin page.
Another way (slightly more complex), involves posting your form data to a generic controller method, passing it a hidden input containing the current URL.
The generic controller method handling your form can then redirect to the page on which the user submitted the form, passing it the validation errors or a success message using flash session variables: $this->session->set_flashdata('errors',validation_errors()) might do the trick (untested)
The good thing about this is that you can use the generic form-handling method for both the ajax case (suppressing the redirect) and the non-ajax case
AJAX would be best, just like everyone else says.
I would redirect the form to one function in one controller, you could make a controller just for the form itself. Then have a hidden value with the return URL. As far as errors go you could send them back with flashdata.
Just remember to never copy paste code, it a bad practice and guarantees bugs.
//make sure you load the proper model
if ($this->form_validation->run() == FALSE){
// invalid
$redirect = $this->input->post('url');
$this->session->set_flashdata('errors',validation_errors());
redirect($redirect);
} else {
/*
success, do what you want here
*/
redirect('send them where ever');
}

Resources