Codeigniter - handle form submission from different controller action - php

Whats the best way to handle the following situation in codeigniter:
Home controller has an index action and a submit action.
The submit action is used for a form submission. I want to load the page through the index controller though - including after form submission i.e. with form errors data to repopulate form inputs on error etc.
Whats the best way to do this - without having the index controller handle the main page loading and the form submission.

If you redirect(), you won't be able to use set_value() for re-populating your form fields.
What's easiest is having your index controller handle both the default load behavior, and the submission.
function index()
{
if($this->input->post('foo'))
{ // something was POSTed
$this->load->library('form_validation');
//validation rules
} else
{ // normal view
//
}
$this->load->view('home');
}
Alternatively, you can just set up your index and submit controller, and have them point at the same view, which detects if validation_errors() are set and re-populates form fields accordingly.
Third option (hackish): you could use flashdata to keep submission errors and the submitted form values across a redirect back to index. Something like this would work:
$this->session->set_flashdata('errors', $validation_errors());

Simply point your form at your submit action:
<form method="post" action="/home/submit">
Then, use the submit action to validate your input before redirecting back to the index action.

Related

Codeigniter controller prevent entire page from reloading when form is validating

Basically, I have my controller function for adding in my case a page but let’s focus on the function:
public function add() {
$this->session->unset_userdata('postID');
if ($this->form_validation->run() == TRUE) {
// Form Validation
}
$this->data['subview'] = 'blah blah';
$this->load->view('blah blah.php', $this->data);
}
Basically when the form is submitted it will still unset the postID in this case, however i want to ensure that if the form is submitted and there are errors that this is missed and it doesn’t redo some of my functions and variables. This is happening for a lot of my content when the form is submitted it re-initiates variables that i want to be ignored.
I also tried the following but it didn’t work either:
if (!$this->form_validation->run()) {
$this->session->unset_userdata('postID');
}
How do i avoid the entire page being redone when the form is validating as it re-performs all the page load content?
Thanks
You can check if the submit button was pushed by using
if($this->input->post('the-name-of-the-submit-button')) {
$this->session->unset_userdata('postID');
}
Basically, $this->form_validation->run() checks if the form was submitted and if it passed validation rules, whereas the above simply checks if the form was submitted at all.
You need to do an ajax submission if you don't want the page to refresh:
http://phpsblog.agustinvillalba.com/sending-forms-ajax-codeigniter/
Alternatively, you can fill in the field values so they don't "RESET", ie <input value="<?php echo $_POST['value'];?>" />, but ajax is a much better solution.
You can return errors in JSON from your codeigniter controller and display them on your page.
If you do any type of request with your browser, the page is always going to refresh, unless you use ajax/javascript.

Javascript form submission with extra parameters / custom redirect

I currently have a form which users can traditionally click on a submit button to save. The form action goes to a page called formProcess.php, which contains a meta-redirect that will save everything then redirect the user back to the form.
I have been requested to add a new feature to a hyperlink on the form page which will automatically save the form before following the hyperlink to a different page. I've currently got some simple jQuery connected to the hyperlink which submits the form like so:
$('#hyperlink').click(function() {
$(this).closest("#save_form").submit();
});
This works and submits the form, but of course formProcess.php has a meta-redirect in it which will take the user back to the form page which I don't want.
I figure if I could pass some extra parameter in the Javascript form submission, like submit('redirect=link'); then I could add something like this to formProcess.php:
if ($_POST['redirect'] == 'link') {
// Redirect 1
} else {
// Redirect 2
}
Is this possible? I can't seem to find any information on being able to pass any extra parameters using submit(); If not, what would you suggest is the best way to tackle my problem?
You can append a temporary field to your form.
$('#hyperlink').click(function() {
$(this).closest("#save_form").append('<input type="hidden" name="redirect" value="link" />');
$(this).closest("#save_form").submit();
});
In your form you can use hidden input type.
Ex.
<input type="hidden" name="redirect" value="link"/>
so when form is submit your hidden field value also to be submit with other parameter.
in your php you can simply do as below:
if ($_POST['redirect'] == "link") {
// Redirect 1
} else {
// Redirect 2
}
You can either use ajax to submit your form and upon success then redirect to the url you want.Without using ajax you could add a hidden field in your form and change it's value.Then server side you ll be able to check the value of you hidden field and act accordingly.

Codeigniter redirect does not update url using jQuery mobile

I have a login controller, which is suppose to redirect to my index page when the user is valid. The redirect works, but at the index page the url is still that of the validation method ex: login/validate_login/. If i click on a link on the index page, and then try and go back in the brower history, the browser points me to the validate method and not the index page.
How do i fix this?
I have tried using redirect with both refresh and location, but both with no luck.
I suspect this is a problem with the ajax call of jQuery mobile, but i'm not sure.
Any help appreciated.
Kind regards
NOTE: I would post an image of the url at the index page, but i'm not allowed to because i'm a new user.
My validate method:
function validate_login($controller='',$method='') {
$this->load->library('form_validation');
$this->load->model('workout_model');
$this->form_validation->set_rules('ex_password','Koden','trim|required|min_length[4]|max_length[4]|callback_pw_check');
if($this->form_validation->run() == FALSE) {
$this->index();
} else {
if($query = $this->workout_model->validate()) {
$data = array(
'is_logged_in' => true,
'user_id' => $query->id,
'current_exercise' => '1'
);
$this->session->set_userdata($data);
if($controller=='' || $method=='') {
redirect("workout");
} else {
redirect($controller."/".$method);
}
} else {
$this->index();
}
}
}
Two things seem to be necessary for the URL to be correctly updated: use redirect(...) instead of method calls AND disable jQuery Mobile ajax call. Two ways of doing that: add and attribute to the link that initially points to your method,
<a href='.../validate_login/...' data-ajax='false'>...</a>
or, disable ajax calls globally by editing the settings (not tested).
There are two ways to handle this and it has nothing to do with AJAX it's the way CI does things. The quickest and easiest way is to change
$this->index();
to
redirect(index);
The way you're doing it you're not actually redirecting, you're calling the index function on the current URL which is validate_login. The problem with doing it this way is if the login fails it will still remain on the validate_login URL for the next try.
The best way to handle it is to have the actual validate_login function called from your index function in the controller rather than the form itself. So send the form back to index, have the index controller check for the form data and if true call validate_login(). That way you're never actually leaving the index page, it just handles whether or not the login form has been submitted. Solving the URL issue. I actually do this with all my pages that submit forms for any kind of validation.
when you submit via HTML form, such as login register .then you have also some kind of dashboard redirection, you need to update your form tag like this.this occurs when I'm using Codeigniter and jquery mobile use data-ajax="false"
<form id="login-box" method="post" action="<?php echo base_url('index.php/auth/login_user'); ?> " data-ajax="false">

Codeigniter: Load View file with #id added on to url to scroll down page

I am using the form validation class in codeigniter. All working fine but when it reloads the form with the errors the page is at the top again. (because it's refreshed). Is there a way I can add an #id onto the end of the url so it will load further down the page where the form is?
I tried redirect('form/form#form, 'refresh') which worked but didnt carry through the errors.
The problem is if you redirect the page then the POST array is cleared. Therefore set_value() can't repopulate your form.
There are a couple of ways you can go about this
Overwrite the session library. Inside this library, stick your post array into a session flash_data on redirect. Then inside your set_value functions ( there are 2 of them ), if you can't find anything in the post array, look for your flashdata.
Don't use the set_value function. Instead, inside your action controller put your form data into flashdata, and inside your form, use $this->session->flashdata('form_field_1'), instead of set_value('form_field_1');
As far as the redirection goes, you're doing it right.
Sorry for being lazy and not posting code. If this isn't clear enough let me know and I can post code.
You're just doing a simple form validation right? If so, you should be able to use set_value to repopulate your form after an error.
http://codeigniter.com/user_guide/libraries/form_validation.html#repopulatingform
If you're using CI's form validation, I'm assuming your form goes back to the controller. The controller should then determine where to go.
if ($this->form_validation->run() == FALSE) {
$this->load->view('form#anchor');
} else {
$this->load->view('formsuccess');
}
You should be able to dynamically set the #anchor tag in your controller based on what errors you get during validation.

codeigniter print form specific validation error

I have 2 forms on a page eg: 'create_user' and 'update_user' i want to show validation errors specific to each form just above the form. i mean, i want to show validation errors for 'create_user' form just above it and same for 'update_user'.
Right now if i submit update, form errors are showing above both of the forms.
is there something like
<? echo validation_errors("create_user"); ?>
You could do something like:
//pass validation_errors as data to your view from your controller, like
//in your controller
if ($this->form_validation->run()) { //form create_user form
//process
}
else {
$data['create_user_form_errors'] = validation_errors();
}
//and for second form update_user
if ($this->form_validation->run()) { //form create_user form
//process
}
else {
$data['update_user_form_errors'] = validation_errors();
}
//then in your view
if (isset($create_user_form_errors)) echo $create_user_form_errors; //show above first form
//and
if (isset($update_user_form_errors)) echo $update_user_form_errors; //show above second form
Something like that should work for showing errors based on multiple forms. Hope it helps
Simplest way is this:
Pass some sort of form-identifying hidden field with each form
Pass that same hidden field to the view error state, and use a basic IF condition to run validation_errors() in the correct location
You could probably extend the validation class somehow to do what you're asking, but it would be a very specific implementation, and hardly useful in a framework (which is why CI doesn't "know how" to do this by default). The added complexity of working with the extended class would likely counteract any benefit of not simply using basic logic in the view.

Categories