Codeigniter Flash Data After Submitting Form? - codeigniter

I have a question regarding form validation with Codeigniter and Flash Data. My form is located deep inside a URL string so I figured the best way to display error message on the page is with CI flash data. I'm having a difficult time figuring out how to actually display the error message. I'm not sure where I'm going wrong. Where am I going wrong? Thanks everyone.
public function form_validate_cars()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
$this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// if person does not fill in correct info, they get resubmitted back to the form.
// redirect('site/item/2332');
// echo 'Hello World!';
$msg = "Please fill out proper data";
$this->session->set_flashdata('test', $msg);
// echo 'Please fill out needed ifnormation!';
}
else
{
$this->load->model('model_data');
$this->model_data->add_new_value();
redirect('/site/thanks');
}
}
My View
echo form_open('site/form_validate_cars');
print_r($this->session->flashdata('test'));
echo validation_errors();
my form continues below .......

Right after $this->session->set_flashdata('test', $msg); make redirect to desired url.
in view
if ($this->session->flashdata('result') != ''):
echo $this->session->flashdata('result');
endif;
better way without session
public function form_validate_cars()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
$this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// if person does not fill in correct info, they get resubmitted back to the form.
// redirect('site/item/2332');
// echo 'Hello World!';
$data['error'] = "Please fill out proper data";
$this->load->view('desired_view', $data);
} else {
$this->load->model('model_data');
$this->model_data->add_new_value();
redirect('/site/thanks');
}
}
and in view
echo (isset($error)) ? $error : "";

After you assigned the flashdata, redirect back to the form with redirect(). This will then pick up the flashdata, make sure to check if it's filled though.

Related

Saving the page state after choosing filters

I have some filters on a web page (checkboxes) and I modify the result list by ajax POST method. Is there a way that somehow I save the page state and send the URL link to someone so they open it in that state? Any help is appreciated.
By the way I'm using Laravel.
You can use parameters :
test.com/page?checkbox1=checked&checkbox2=checked
In your Laravel controller you can do this :
public function page($request) {
$checkboxes = array();
if ($request->has('checkbox1')) {
$checkboxes[] = true;
}
if ($request->has('checkbox2')) {
$checkboxes[] = true;
}
// ... and so on.
return view('page', compact('checkboxes'));
}
And set your php page like this :
<input type="checkbox" <?php checkboxes[$i++] ? 'checked' : '' ?> >
You can set the checkbox as parameter in the URL, and when the user go to your address, check if there is any of your params.
if so - set the checkboxes as you wish
just to get the general idea..
function getUrlParams(requested_param){
//check for params
return result;
}
if (getUrlParams(myCheckBox)){
$('#checkbox_on_page').prop( "checked", true );
}

How to repopulate form after form validation and also keep the URI?

I have a problem repopulating my form after validation fails. Problem is my url contains an additional uri which I access by clicking a link. This is what it looks like:
http://www.example.com/admin/trivia/add/5
At first trouble was that the segment 4 of the uri completely disappeared, so even though the validation errors showed and the form was repopulated, I lost my added uri.
Then I found in another question that the solution was to set form open like this:
echo form_open(current_url());
Problem is now it isn't showing any validation errors and the form is not repopulated. Is there a way to achieve this?
This is what my controller looks like:
function add()
{
$data = array('id' => $this->uri->segment(4));
if($_POST)
{
$this->_processForm();
}
$this->load->view('admin/trivia_form', $data);
}
And inside _processForm() I got all the validation rules, error message and redirecting in case success.
[edit] Here is my _processForm() :
function _processForm()
{
$this->load->library('form_validation');
//validation rules go here
//validation error messages
$this->form_validation->set_rules($rules);
$this->form_validation->set_error_delimiters('<div style="color:red">', '</div>');
if ($this->form_validation->run())
{
//get input from form and assign it to array
//save data in DB with model
if($this->madmin->save_trivia($fields))
{
//if save is correct, then redirect
}
else
{
//if not show errors, no redirecting.
}
}//end if validation
}
To keep the same url, you can do all things in a same controller function.
In your controller
function add($id)
{
if($this->input->server('REQUEST_METHOD') === 'POST')// form submitted
{
// do form action code
// redirect if success
}
// do your actual stuff to load. you may get validation error in view file as usual if validation failed
}
to repopulate the form fields you are going to need to reset the field values when submitting it as exampled here and to meke it open the same page you can use redirect() function as bellow:
redirect('trivia/add/5','refresh');
i don't know what you are trying to do, but try this to repopulate the form with the values user entered
<?php
echo form_input('myfield',set_value('myfield'),'placeholder="xyz"');
?>

Drupal Form API : display the same form again with AJAX, but with different values, on submit

this is my first post on Stackoverflow, after reading perhaps hundreds of thoughtful questions and no less useful answers.
My point is, today, I never found an (even dirty) way to do what I intend to do, and never managed to find an answer, although it seems quite improbable that no one ever had the same request and/or problem.
Which is, by the way...
Calling the same form again with AJAX, but with different values than those previously entered by the user
The idea
I've got a Drupal Form (a normal form built with Drupal Form API) with textfields and an AJAX-ified submit button. This form is displayed through an AJAX call and is itself AJAX-ified, so.
When I click on 'Submit', I want to do some stuff like looking in the database, updating some values, etc, based on what the user entered in the form. And then, I want to ajax-display the same form again, but with different values than those entered by the user in the first instance of the form.
Everything goes fine with doing whatever I want during the processing, but whatever I do, no matter what, I face the same problem again and again :
The problem
When the new instance of the form is displayed, it is displayed with the previous values (those entered by the user). I never was able to display other values than those previously here in the form when "Submit" was clicked in the previous instance of the form.
Simple example
What I'm actually trying to do is quite complex, with several ajax_commands and a bit of processing, but here is a simpler example that faces exactly the same problem :
function ajax_first_callback_to_my_form($type = 'ajax') {
// here the first instance of the form is ajax-called. No problem with that.
$mail = 'example#mail.com';
$first_message = 'Please enter an email address...';
$commands = array();
$commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($mail, $first_message));
$page = array('#type' => 'ajax', '#commands' => $commands);
return($page);
}
function display_my_form($mail, $message) {
// the function used to display the form.
// it can be called by the first ajax callback (the previous function in this example)
// or by the ajax callback triggered by clicking 'submit' on the form itself.
$form = drupal_get_form('my_form', $mail, $message);
$display = '<div id="my_ajax_wrapper">';
$display .= render($form);
$display .= '</div>';
return $display;
}
function my_form($form, &$form_state, $mail, $message) {
// the form constructor
$form = array (
'email' => array (
'#type' => 'textfield',
'#default_value' => $mail,
'#suffix' => '<div id="my_message">'.$message.'</div>',
),
'submit' => array (
'#type' => 'submit',
'#ajax' => array (
'callback' => 'my_ajax_callback', ),
),
);
}
function my_ajax_callback($form, &$form_state) {
// triggered by clicking 'submit' in the form
$mail = $form_state['values']['email'];
if ($mail == 'correct_mail#gmail.com') {
$new_mail = 'different_mail#gmail.com';
$new_message = 'You entered a correct email and here is your new one';
} else {
$new_mail = $mail;
$new_message = 'You entered an incorrect mail, please correct it';
}
$commands = array();
$commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($new_mail, $new_message));
$page = array('#type' => 'ajax', '#commands' => $commands);
return($page);
}
function my_form_submit($form, &form_state) {
// my_form submit handler
$form_state['rebuild'] = true; // appears necessary, otherwise won't work at all
}
Okay, it was quite a long piece of code but it seemed useful to fully understand my question.
Processing stuff happens correctly...
All the stuff I want to do in my_form_submit or in my_ajax_callback is properly done. If I check the variables in display_my_form() they are correctly updated.
... but the new instance of the form doesn't take it into account
But whatever I can try, the next time the form is displayed with AJAX, the email field will be 'example#mail.com' as its default value (or any different mail entered by the user), and the message div will be filled with 'Please enter an email address...'.
I tried MANY ways of doing this differently, putting the after-submit processing in the ajax callback, in the my_form_submit function, using $_SESSION variables instead of passing them through the different functions, using the database... None of this works.
What to do ?
Quite annoying. This is not the first time I encountered this problem. Last time I could find a workaround, simply by giving up this idea of re-displaying the same form through AJAX, but now I really would appreciate being able to do this.
Could the problem be related to $form_state['rebuild'] ?
By the way, I'm curious about it : have you encountered this problem before ? Is it something simple which I'm missing out ? If it's a bug, could this bug be Drupal-related, or AJAX-related... ?
Any help or ideas will be truly appreciated. Thank you for your time.
I came up with a solution to this one :
If you are to display the same form again with AJAX, for instance with this function (called by your AJAX callback), no matter what you'll do, it will display the same values again and again :
// It doesn't work :
function display_my_form($mail, $message) {
$form = drupal_get_form('my_form', $mail, $message);
$display = '<div id="my_ajax_wrapper">';
$display .= render($form);
$display .= '</div>';
return $display;
}
If you want to change the fields values when refreshing the form, you have to update the form manually, after having called it again, by adding this kind of line :
// It works :
function display_my_form($mail, $message) {
$form = drupal_get_form('my_form', $mail, $message); // $variables are simply ignored if the form is already displayed. Rebuilding it won't change a thing.
$form['email']['#default_value'] = $mail; // update a part of the form
$form['email']['#suffix'] = $message; // update another part of the form
$display = '<div id="my_ajax_wrapper">';
$display .= render($form);
$display .= '</div>';
return $display; // sends $display to our AJAX callback, and everything's fine now
}
Contrary to easy belief one (such as... me) can first have about it, the form doesn't take into account the variables it's being sent with drupal_get_form, when already constructed and recalled by AJAX.
It's just not enough to update the variables, and do drupal_get_form again. You have to do drupal_get_form, and afterwards manually update the parts of the form you want updated.
Hope this will help someone.
Well I am quite confident about your issue if this is the case:
$commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($new_mail, $new_message));
The problem is not anything else its just the id you are passing.You need a class and not the id "#my_ajax_wrapper", because id might get changed but class won't in this case.
Try with this you should get the result as you want.
Note: to make it work, one needs to add this in form_submit handler:
function my_form_submit($form, &$form_state)
{
$form_state['rebuild'] = true;
}

Codeigniter controller detecting ajax file upload

I have set up my Codeigniter application so that I can upload files via Ajax. I followed this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/how-to-upload-files-with-codeigniter-and-ajax/
My original form checked to see if an ajax request had been called, if not then I had the fallback CI form validation / error messages showing instead.
I checked this using - $this->input->is_ajax_request()
My code looked like this:
if($this->input->is_ajax_request()){
// process ajax form data
} else {
if($this->form_validation->run() == FALSE) {
$data['success'] = 0;
$data['errors'] = validation_errors();
} else {
$data['success'] = 1;
}
$this->load->view('form', $data);
}
After doing some investigation I discovered that I couldn't apply the same technique because it isn't actually an ajax request, therefore I am not sure how I can use this approach. If anyone can point me in the right direction that would be great. I don't like it being totally dependent on ajax, I like having a fallback option. I noticed in the comments that someone has set up a CSFR cookie in their ajaxfileupload.js but to be honest I'm not too hot with js so I wouldn't know where to begin. Thanks in advance.
In your AJAX request along with everything else you could post key/value:
ajax : 1
Then in your controller:
if( $this->input->post('ajax') == 1 ) {
// process ajax form data
}
else
{
// form validation
}
Hope this helps.

Recaptcha with CodeIgniter

I am trying to implement recaptcha my form in CodeIgniter (without using the recaptcha library). This works fine, however as in my form, I am displaying each fields errors individually, I want to display recaptcha error next to its place in the form, can someone help me how can i do it?
The code from my controller:
$this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]|max_length[25]');
$this->form_validation->set_rules('email', 'Email address', 'trim|required|valid_email');
//With above set_rules i'm able to display each fields errors next to it,
//How can i display following recaptcha error next to it.
if (!$resp->is_valid)
{
//reCAPTCHA was entered incorrectly
die (
"The reCAPTCHA wasn entered incorrectly." .
"(reCAPTCHA said: " . $resp->error . ")
");
}
else
{
//Successful verification
die('Success!');
}
Thanks for any help.
If you aren't running the recaptcha field through the form validation library you won't be able to use the form_error() function, but you can easily send the error to your view as a variable:
if ($this->form_validation->run())
{
if ( ! $resp->is_valid)
{
$data['recaptcha_error'] = "reCAPTCHA said: ".$resp->error;
}
else
{
// Process form
}
}
$this->load->view('my_view', $data);
Then in your view (wherever/however you want):
<?php if (isset($recaptcha_error)): ?>
<label class="error">
<?php echo $recaptcha_error; ?>
</label>
<?php endif; ?>

Resources