I have a form. On - laravel

I have a form. When validation fails i redirect to the same page. "mobilepage1.blade.php"
But all my entries are all gone. I want all my entries to stay. Exept the password.
I redirect my page with View::make
return View::make('mobilepages.mobilepage1', array('errormessages' => 'errormessages'));
I use:
$input = Input::all();
to get the input.

All input
return Redirect::to('mobilepages')->withInput(Input::all());
Except password
return Redirect::to('mobilepages')->withInput(Input::except('password'));
Old Input

In your form view, use something like this for the inputs:
<?= Form::text('title', (Input::get('title') ?: NULL)); ?>
The (Input::get('title') ?: NULL) operator will return the previous title value if it was set and nothing if it wasn't set.

It should be done using something like this:
public formSubmitMethod() // Change formSubmitMethod with appropriate one
{
// This is the form submit handler
// Set rules and validate the inputs
$rules = array(...); // set rules here but there are other ways
$inputs = Input::except('_token'); // everything but _token
$validatior = Validator::make($input, $rules);
if($validatior->fails()) {
// Validation failed
return Redirect::back()->withInput()->withErrors($validatior);
}
else {
// Success
// Do whatever you want to do
}
}
In your form, use Input::old('fieldname'), something like this:
{{ Form::input('username', Input::old('fieldname')) }}
That's it, now if you redirect back for invalid user inputs then your form fields will be repopulated with old values. Don't use old() method in the password field. You can also access the error message for a field using something like {{ $errors->first('username') }}, so if this (username) field invalidated then the error message for this field will be printed out.
Also, notice that, to redirect back, I've use Redirect::back() not View::make(), it's (make) not for redirecting but for rendering a view to show it.

Related

Laravel 5.7: Too many redirect after Validation failed

I have a two step form, after the input on the first page gets validated a second page to upload a file will be displayed.
Here's the validation rules for the file input:
return [
'file' => 'mimes:pdf,ps|required',
];
When I try to submit the form without attaching a file then I get the message that I've been redirected too many times.
Here's also a custom middleware I created to set the locale that's needed for the urls:
public function handle($request, Closure $next)
{
$locale = $request->segment(1);
app()->setLocale($locale);
return $next($request); // this is the marked line
}
I have no 'get'-route for the second form-page since it will only display after the first user input is validated.
After creating a 'get'-route it still didn't work and I still got redirected too many times.
Route::post('/{locale}/ticket/{cat?}', 'TicketController#store')->name('validation');
Route::get('/{locale}/ticket/{cat?}', 'TicketController#store')->name('validation');
I even tried to do this:
Route::match(['post', 'get'], '/{locale}/ticket/{cat?}, 'TicketController#store')->name('validation');
after reading about this, but it still didn't work and know I really don't know what to do.
I only get redirected too many times when the second validation fails, when I don't require the file (in the validation rule) and the validation doesn't redirect then the upload-method just continues as it should.
EDIT:
This is the upload-method in the TicketController as requested:
public function upload(ValidateUploadedFile $request, $cat = '') {
// handle first user input
$file = $request->validated();
// handle storage of data
}
I don't have any idea how to solve this issue.
If any more code or information is needed to help me, please tell me!

Form input values not remain after flash error message

How to solve above issue? I want to keep test even after a validation failure in the submission. But after session error message is passed all the entered data will be gone.
To re-fill the form with the input data again, check the input validation then if validation fails, redirect the user back along with his input data and validation errors.
$validator = Validator::make($request->all(), [
// your validation rules.
'name' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
// Continue your app logic.
You'll find more information in Laravel validation docs
You should send back the input also to the view.
Like Sameh Salama already mentioned, use the following code:
function () {
return redirect()->back()->withErrors($validator)->withInput();
}
Notice the withInput() function, it returns the old input.
Use it in the View as
<input type="something" value="{{$input->first_something}}" />

change any rule in codeigniter to match function

I have set up my routes.php to suit the nature of my site. Unfortunately, there is a problem with my last route i.e.:
$route['(:any)'] = "profile/profile_guest/$1";
If the username password name passed is correct, for e.g. domain.com/username, it will load his/her data. if not, it loads the page with errors (because failure to retrieve data with non-existent user in database). This is my problem! I want to avoid this error showing.
Is there anyway I could avoid this error from happening? None of the echoes seems to be printing or the redirect neither is working. Don't know why! it is as if the code inside this method is not executing and the view is loaded instead. below is part of the profile_guest function:
public function profile_guest($username)
{
$username = $this->uri->segment(1);
//echo "Hello " . $username;
redirect('main', 'refresh');
if($username != '')
{
/* echo "<h1>HELLO WORLD SOMETHING</h1>"; */
It's hard to say without seeing the rest of the code.
Maybe you need to check the value before running the query:
// user_model
function get_user($username = NULL){
if($username){
return $this->db->query(...
}else{
return false;
}
}
Then check that the query returned anything before loading the view
if($this->user_model->get_user($username){
//show the page
}else{
echo "no user found";
}

How can I debug $Model after validation?

I want to see the content of validationErrors => array(???) of the $Model after a failed validation, but there is no "afterValidation()" method.
Does anyone know how can I see that or at least how would it look exactely?
Thank's!
On Controller, you can validate data before you trying save:
$this->ModelName->set($this->request->data);
if ($this->ModelName->validates()) {
// success
} else {
// failed
$errors = $this->ModelName->validationErrors;
}
Reference:
Validating Data from the Controller
Use $this->ModelName->invalidFields() after you have made the save/whatever you're doing:
For example:
debug($this->ModelName->invalidFields());
If you have a redirect at some point after that call, you might not see the data in your view. In this case, you can always do die(); either right after or wrapped around your call like so:
die(debug($this->ModelName->invalidFields());

Codeigniter form validation failing when it should succeed

I'm building an admin utility for adding a bulk of images to an app I'm working on. I also need to to log certain properties that are associated with the images and then store it all into the database.
So basically the script looks into a folder, compares the contents of the folder to records in the database. All of the info must be entered in order for the database record to be complete, hence the form validation.
The validation is working, when there are no values entered it prompts the entry of the missing fields. However it happens even when the fields ARE filled.
I'm doing something a bit funny which may be the reason.
Because I'm adding a bulk of images I'm creating the data within a for loop and adding the validation rules within the same for loop.
Here is the results:
http://s75151.gridserver.com/CI_staging/index.php/admin_panel/bulk_emo_update
Right now I have default test values in the form while testing validation. The submit button is way at the bottom. I'm printing POST variable for testing purposes.
Here is the code:
function bulk_emo_update() {
$img_folder_location = 'img/moodtracker/emos/';//set an image path
$emo_files = $this->mood_model->get_emo_images('*.{png,jpg,jpeg,gif}', $img_folder_location); //grab files from folder
$emo_records = $this->mood_model->get_all_emos(); //grab records from db
$i=1; //sets a counter to be referenced in the form
$temp_emo_info = array(); //temp vairable for holding emo data that will be sent to the form
//loop through all the files in the designated folder
foreach($emo_files as $file) {
$file_path = $img_folder_location.$file;//builds the path out of the flder location and the file name
//loops through all the database reocrds for the pupose of checking to see if the image file is preasent in the record
foreach($emo_records as $record) {
//compairs file paths, if they are the
if($record->picture_url != $file_path) {
//FORM VALIDATION STUFF:
$rules['segment_radio['.$i.']'] = "required";
$rules['emo_name_text_feild['.$i.']'] = "required";
//populating the temp array which will be used to construct the form
$temp_emo_info[$i]['path'] = $file_path;
$temp_emo_info[$i]['name'] = $file;
}
}
$i++;
}
//sets the reference to validation rules
$this->validation->set_rules($rules);
//checks to see if the form has all it's required fields
if ($this->validation->run() == FALSE) { //if validation fails:
print_r($_POST);
//prepairs the data array to pass into the view to build the form
$data['title'] = 'Bulk Emo Update';
$data['intro_text'] = 'fill out all fields below. hit submit when finished';
$data['emos_info'] = $temp_emo_info;
$this->load->view('admin_bulk_emo_update_view',$data);
} else { // if it succeeds:
//printing for test purposes
print_r($_POST);
$this->load->view('form_result');
}
}
I'm new to codeigniter and php in general so if anything looks outrageously weird please tell me, don't worry about my feelings I've got thick skin.
if ($this->validation->run() == FALSE)
if you are calling the run() method of the validation class every time the script is run, will it ever return TRUE and run the else? Maybe a different return?
I'm a little cornfused by what's going on. Generally, if I'm having a problem like this, I will figure out a way to force the result I'm looking for. e.g. in your code, I'd force that else to run... once I get it to run, break down what happened to make it run. Rudimentary, but it has served me well.
You use array of rules in
$this->form_validation->set_rules()
wrong.
If you want to pass the rules in array you must stick to the key names like described here http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray
So instead of
$rules['input_name'] = "required"
try this:
array(
'field' => 'input_name',
'label' => 'Name that you output in error message',
'rules' => 'required'
)

Resources