Multiple file input and form validation? - php

I have multiple files and input text in my form. My code is :
if(formValidationIsGood) {
if(customeCheckFileErrorIsEmpty) {
//StartProcess
}
else {
//I load my view with my array which contains the different error related to the files.
}
else {
//I load my view with the form error (set up by : $this->form_validation->set_rules('variable', 'Variable', 'required');) But if there is an error for the files I cant display it.
}
With this code I can't show the form error and the files error at the same time.
For example the user, is uploading an csv file instead of a pdf file, and he forgot to write into a text input, the form error will be displayed but not the file error and vice versa.
Obviously I am using the helper file provide by code igniter.

Since you want to display error messages for either A OR B, you can try this:
if (!formValidationIsGood || !customeCheckFileErrorIsEmpty)
{
// load the view and display whatever errors you found
}
else
{
// form validation IS good and the files error is empty
}
The if clause above will evaluate to true if either formValidationIsGood ISN'T true (the ! prefix is key) OR the customeCheckFileErrorIsEmpty ISN't true (which would mean there is an error)

Related

Friendlier form validation with error logging on all inputs

I am tying to refine how my application handles drawing forms and validating their inputs. In particular, I want the option of testing ALL inputs for validation instead of just returning on the first error I find! I'd like to accomplish a structure like this...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (check_field($_POST['name']))
{
$form_errors['name'] = 'Name is invalid';
}
if (check_field($_POST['email']))
{
$form_errors['email'] = 'E-mail is invalid';
}
if (count($form_errors) == 0)
{
// All validations succeeded
// Continue processing the form
// Show confirmation for user
// DO NOT REDRAW THE FORM!!!
}
else
{
// Somehow jump to the SHOW_FORM below
}
}
elseif (SHOW_FORM)
{
// Show ALL errors we have collected, if any
print_r($form_errors);
/*
* A block of code that draws the form!
* A block of code that draws the form!
* A block of code that draws the form!
*/
}
else
{
// Show a list of records to edit
}
I have been accomplishing this with functions up until now. I have 1.) a function that draws the form and prints the contents of the $form_errors array if any and 2.) a function that validates the form inputs on submission. If the validation function returns false (which it does if any errors are found), the user lands back on the form with all of their errors on display.
Writing a pair of functions for every new form has become cumbersome and leads to a lot of repeat code. If possible, I'd like to abandon this practice and just have my parent page validate form inputs, but default to simply drawing the form. I would like assistance in structuring the page in this way.
Here's some ideas:
Put your forms into their own files with nothing but the html & code to display errors only (this is called a View).
Post to a page that handles the post (this is called a Controller).
In the page that handles the post, only validate using re-usable functions that you have included from another file. For example the validation function might look like this: validate_email($_POST['email']); or validate($_POST['email'], 'email');, or validate($_POST, ['email' => 'email']);

Display custom error message in MVC view with PHP

I need to display user friendly error message in the view I am in, and wondering what will be the best solution. I can display and error page using error controller but this is not what i want to achieve. I need to handle all custom error messages in any model and display an error in the view you are in. For example:
I am in "user" controller. When creating new user, the PHP model code checks if same user name exist, if exist I want to display a message in the view or maybe have something like this in header: echo $error; which display any error message I have set to be displayed from any model if occurred.
Example error message in model:
if ($p0 > 0) {
$IsValid = false;
log::LOG_USER_ERROR("This user already exist!", $username);
exit("This user already exist! </br> ");
}
This code write the error in a log file successfully, however how do I display the error message in the same view I am in? exit() displays the message in a blank page. I need to display it as block in red in the same view and design.
exit() terminates the current script, so the code for your View is not executed.
Instead, part of your View should be an area to display messages. Then you can put the error message in a variable (probably an array of messages) that the View displays to the user in that area.

Yii: Keep files uploaded after validation fail?

If I upload a file with YII and another rule fails, then the user has to pick the file again. What is the easiest way to avoid this?
For example, I have a rule that the title must be 20 characters at most. The user types in 21 letters. He chooses a file to upload. When the user is returned to the page, the file is no longer there and he must choose it again, and effectively upload it again. This is very frustrating, especially now when the user will be required to upload up to ten files.
I know Drupal works like this. If you upload and other rules fail, the files appear as screenshots when you return to the form. How can I get the same functionality on YII?
UPDATE
If I could get that requirement covered with this extension and not require that the user presses start upload, I would be home free
The original plugin that xupload wraps, there is an additional callback option you could use: .done().
In the xupload wiki, the way to access those additional options would be this way:
<?php
$this->widget('xupload.XUpload', array(
// ... other attributes
'options' => array(
//This is the submit callback that will gather
//the additional data corresponding to the current file
'submit' => "js:function (e, data) {
var inputs = data.context.find(':input');
data.formData = inputs.serializeArray();
return true;
}"
),
));
?>
Source
You could probably just change the submit part to done, and let that save the URL/path of the uploaded file to a temporary hidden field, and move your validation to that hidden field instead, so the user does not have to re-upload a file again.
I moved away from this plugin to the coco uploader as it was easier to implement.
You could enable client side validation and AJAX validation. So your regular attributes will be validated before the form is sent and the file gets uploaded.
You can do it with session.
In your controller
// Here I have taken Users as model. you should replace it as your need.
$model=new Users;
if(isset($_POST['Users']))
{
$model->attributes=$_POST['Users'];
//save file in session if User has actually selected a file and there weren't any errors.
if(isset($_FILES['Users']) && $_FILES['Users']['error']['image'] == 0){
Yii::app()->session['image'] = $_FILES['Users'];
}
if(isset(Yii::app()->session['image']) && !empty(Yii::app()->session['image'])){
$model->image = Yii::app()->session['image'];
$model->image = CUploadedFile::getInstance($model,'image');
}
if($model->save())
{
if(!empty($model->image)){
$model->image->saveAs(Yii::app()->basePath.'/images/'.time()."_".$model->image->name);
unset(Yii::app()->session['image']);
//File has successfully been uploaded.
}
// redirect to other page.
}
}
else{
// remember to unset the session variable if it's a get request.
unset(Yii::app()->session['image']);
}
And in your view file
//Your form fields
//This is to show user that he has already selected a file. You could do it in more sofisticated way.
if(isset(Yii::app()->session['image']) && !empty(Yii::app()->session['image'])) {
echo "<label>".Yii::app()->session['image']['name']['image']."</label><br>";
}
//File uplaod field.
//More form Fields.
Hope that helps.

Determining if a file was submitted with codeigniter

I basically have an edit profile page that along with other fields has a option to upload a picture. Now the problem I have is determining wether or not they submitted a file or left it blank(default).
My current code:
if($this->input->post('user_pic') === FALSE)
{
//Don't do anything.
} else {
//Proccess upload.
}
The form is done correctly with multi-part and all, and other values do update, so I am assuming that this exact code that isn't working.
The problem is that even if I do submit a file it remains just like it was, or another words doesn't do anything. Am I doing this wrong?
you can check so: if(isset($_FILES['user_pic']))
CodeIgniter method:
$this->load->library('upload');
if ($this->upload->do_upload('user_pic'))
//good
else
//errors display $this->upload->display_errors()
CodeIgniter File Uploading Class

How to implement a form validation page that also displays the result?

Currently, I am having one page that display query options and does the form validation and another page that process the query and shows the result if validation is successful. I am trying to combine these two pages together such that the user would not need to go back and forth the two pages every time to make some query changes.
The structure of the two page process is as follows:
**Validation Page**
if (post detected)
{
validate input
if (no error)
{
record query options
redirect to results page
exit
}
else
{
output error message
}
}
display form
**Results Page**
if (query options are set)
{
process query
display results
}
else
{
redirect to validation page
}
I have seen the concept being implemented simply in search engine pages where the search box and the results are in one page. I am looking to implement something like that using the POST method with a form containing both select and input boxes.
You can just set the form action to itself (or leave it blank along the lines of action = "" and it will point to itself anyhow, then use a simple check to see whether any form data has been submitted to determine if you should show the empty page or the search results:
if(isset($_REQUEST['searchStuffs']) // Not sure if you are GET or POST'ing
{
if(!empty($_REQUEST['searchStuffs'])
{
// do stuff here to get the form result, then display it
}
else
{
// The form was submitted empty, so show an error
}
}
else
{
// Display the normal search/form page as it hasn't been sent.
}
You can also use the following approach (which I would probably use though it is some extra work):
$searchBool=false;
if(isset($_REQUEST['searchStuffs']) // Not sure if you are GET or POST'ing
{
if(!empty($_REQUEST['searchStuffs'])
{
if(...)// valid search criteria
{
$searchBool=true;
// Do stuff to get search results
$searchResults='some output or data';
}
}
}
// Echo normal input form
if($searchBool)
{
echo $searchResults;
}

Categories