CodeIgniter Form Validation with existing $_POST data - codeigniter

I have a form that I need to validate but I can't figure out how to code the controller so that it works correctly the first time the page is displayed. Here is my code (simplified):
function index()
$data['somedata'] = $this->input->post('somedata');
$this->form_validation->set_rules('event', 'Event', 'trim|required|alpha_numeric');
... more set_rules ...
if($this->form_validation->run() == FALSE)
{
// Hasn't been run or there are validation errors
$this->load->view('eventview', $data);
}
else
{
// Process the event
}
}
The problem is that form_validation->run() is never FALSE because the $_POST array contains data from a previous form that is used by this second form. At the very beginning of the form_validation->run() function is the following code:
// Do we even have any data to process? Mm?
if (count($_POST) == 0)
{
return FALSE;
}
Since $_POST data exists the count is always greater than zero which results in the validation to be processed on initial page load.
Any suggestions as to how I might work around this?

I would suggest that you save the data from your first form in sessions, then make a redirect to your second form instead of going directly to the next one, with your post data.
This would also be more flexible if you need to reuse any of the submitted data.

In the first form set a hidden input
<input type="hidden" name="form1" value="form1" />
Then in your controller check if the field is set, if so store the current post array, and then unset it.
if(isset($_POST['form1'])){
$old_post = $_POST;
unset($_POST);
}
as I assume you are accessing the $_POST array in your view, instead pass `$old_post` through and use that,
e.g. (isset($old_post) ? $old_post['field_name'] : set_value('field_name))
Good luck.

Related

Get Input Data Value in Controller in Laravel

I want to get the value of this input.
<input type="text" name="txtEmployeeNo" value='{{ $employee->employee_no }}'>
Its value is 53210. How can I get that in my controller?
I currently have this on my controller.
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where(['employee_no'=>$employeeNum])->get();
return view('admin.employeemaintenance.createSchedule',compact(,'employeeSched'));
The problem is when I open and see if it is fetched nothing is showing. I cannot get the input.
Try this, It should must work.
$employeeNum = (isset($request['txtEmployeeNo'])) ? $request['txtEmployeeNo'] : 0;
$employeeSched = Schedule::where(['employee_no'=>$employeeNum])->get();
return view('admin.employeemaintenance.createSchedule',$employeeSched);
In your controller insert this line after opening your function:
dd($request->all);
It will show you everything that has been posted through your form with values. If you get your 'txtEmployeeNo' without value, it means something went wrong when you insterted it in your input.
Check with dev tools if that specific input has any value.
If your input has the value you mentioned and your $request->all() still shows an empty value for your "txtEmployeeNo", then the error is in the HTML/Blade file.
Make sure you create the form correctly
Make sure your input's name equals with the request you are trying to receive in your controller.
If you get null as the value of the $request, that could mean, in your Blade file, the input also has it's value as null.
Try to manually insert a value like <input type="text" name="txtEmployeeNo" value="2"> and see if you get that in your controller. If you do, then the query in your input is wrong.
That's all I could think of without provided Blade and Controller code.
Try this:
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where('employee_no', $employeeNum)->get();
return view('admin.employeemaintenance.createSchedule',compact('employeeSched'));
well, here is an edit to this answer with the steps needed:
in your routes:
Route::post('yourRouteName','yourController#nameOfFunctionInController')->name('TheNameOfTheRoute');
In your controller:
public function nameOfFunction(Request $request) {
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where('employee_no', $employeeNum)->get();
return view('admin.employeemaintenance.createSchedule',compact('employeeSched'));
}
And that's it basically.

How do I auto fill field values in a section of a form that is loaded via ajax in Laravel 4?

I have a section of a form that dynamically loads different sets of fields based on the user's selection in a control. I'm using a javascript event handler to detect when the selection changes, and using AJAX (with HTML payload) to pull in the proper set of fields.
I would like to be able to use Laravel's Form::getValueAttribute() method to automatically fill in the form fields' values in both the static and dynamic form parts. However, the partial view that is loaded by my AJAX call does not have the same instance of the Form class as the view with my main Form, so I can't simply call getValueAttribute() in the partial.
My thought is to make the AJAX call a POST, and serialize the necessary data (a subset of Input::old() or the model data depending whether the page is loaded as the result of validation errors, or an UPDATE request) to send along with the POST so that the HTML fragment I get back has the values set properly.
Is this the best way to get what I want? If so, does Laravel have any tools to help with the serialization of form data? If not, what might be a better approach?
I've found an approach I like better. When the view is loaded normally I use AJAX as usual to load the partial. But when the view is loaded for a validation post-back or for editing, I use Laravel's Views' nest method to nest the partial view containing the proper fields directly into the response. The partial then has access to all the Input and error data I need. The user is still able to change the field set as usual but I put up a confirm prompt for them if they have already set some values in a field set they previously selected. If they decide to proceed anyway, the field set is cleared and a new field set is brought in via AJAX as usual.
My code looks something like this:
Controller:
public function newThing() {
if ( Request::session()->has('errors') ) {
// this is a validation post-back
return View::make('thing')
->nest('fields', 'fields_partial');
} else {
// just a normal unfilled form
return View::make('thing');
}
}
public function editThing() {
return View::make('thing')
->nest('fields', 'fields_partial');
}
View: thing.blade.php (just a snip of it)
...
<form>
...
<select id="picker">...</select>
<div class="sub-fields">
{{ isset($fields) ? $fields : '' }}
</div>
...
</form>
...
<script>
$('#picker').change(function() {
// if any .sub-fields inputs have been changed, get confirmation from the user
// if user confirms, do ajax stuff to replace .sub-fields contents with new field set
// otherwise cancel the change
});
</script>

Codeigniter add validation for multiple element

My form has more than 50 different text inputs. I would like to use CodeIgniter's validations (like trim function) in the form validation library without creating a rule for each input. Is it to possible to combine them into one rule so I don't have to waste my time writing the same code over and over?
Change text field name as group_name[your_txt_names] in your view
<input name="group_name[your_txt_names]" value="" type="text" />
Then in controller, you can create a function.
$txt_bxes = $this->input->post("group_name");
$post_vals = array_map('trim', $txt_bxes);
Now you have trimmed values in your array.
Kumar_v's idea was on the right track, if a bit silly in implementation
$this->input->post('var); merely reads the $_POST and runs some sanitation on it; the validation rules merely read the var from $_POST and apply your validation rule.
So if you only want to trim all $_POST vars, just trim your $_POST directly, then you can also run other validation afterwards.
Solution:
$_POST = array_map('trim', $_POST);
or
// take all posts and dump them into a variable at once
$input = $this->input->post(null, true);
$input = array_map('trim', $input);
as the post data comes in array, I hope this will help you
$postData = $this->input->post();
array_walk($postData ,'myFunc');
function myFunc(&$value,$key){
$value = trim($value);
}

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"');
?>

codeigniter: Return form validator results as string

I'm new to codeigniter so sorry for the simple question.
I want to run formvalidator for my ajax process. How can I return the valdiation errors as JSON? Is there a better way to do this?
Thanks
you haven't really stated what you are doing. i am going to assume that you have a form that you want to save data in, using ajax, so that you don't have any of those pesky save/submit buttons. also, i am guessing that you have some sort of .change() handler that sends the form element to the ajax handler as a post variable as a name/value pair.
the problem you will run into, is that when you run the form validator on your data it will always fail. because the form validator needs all of the fields for that form, and you will only send one piece of data at a time.
normally in the code igniter example code you check to see if the 'run' method passess or not. in your case it doesn't really matter because it will always fail, so don't bother checking. here is a snippet of some example code
$this->form_validation->run('form'); // it is likely that the form won't validate, but thats ok.
$validation_error=form_error($field_name);
if($validation_error){
$feedback = 'Field <strong>NOT</strong> saved.';
}else{
// no errors, we can save.
$this->my_model->set_field($id,$field_name,$field_value);
$validation_error=' '; // this is set so if the field was initially not validated, and it is later, the validation message goes away.
$validation_element = '#'.$field_name;
$feedback = 'Field saved.';
}
....
echo json_encode(array('feedback'=>$feedback,'validation_element'=>'#'.$field_name,'validation_error'=>$validation_error));
break;
in my snippet, a json object is returned to the ajax post. in the jquery ajax post,the success handler has this snippet of code.
try{
var json = $.parseJSON(data);
if(typeof(json.container)==='string'){
var container=json.container;
}
if(typeof(json.html)==='string'){
var con = $(container);
$(con).html(json.html);
}
if(typeof(json.feedback)==='string'){
display_feedback(json.feedback);}
if(typeof(json.validation_element) ==='string'){
// assumes that if a validation_element object is returned, it has a paired validation_error element.
$(json.validation_element).closest('.col_b').nextAll('.validation_error').first().html(json.validation_error);
}
}
catch(err){
display_feedback(err);
}
in my form, i have a three column format, where:
<div class='col_a'>label</div>
<div class='col_b' >input, id = field_name </div>
<div class='col_c validation_error'>validation text</div>
hopefully that makes some sense to you.

Resources