How to validate many fields combined in Codeigniter? - php

Is there a creative and easy way to check many form fields at once.
I have a form with generated fields on the fly, each has a unique id.
The thing is submitting all the fields are not required, but at least one field must be filled before submitting.
Is there a way to do this in Codeigniter, or how would I go about validating this effectively.
I understand that it is possible to check each field individually, but I'm seeking for a much cleaner way.
I hope it's clear for you guys. Thanks.

Try this:
$_POST['data_you_want_to_validate_together'] = $_POST['first_field'] . $_POST['second_field'];
$this->form_validation->set_rules('data_you_want_to_validate_together','Some Data', 'required|callback_some_function');
Now you can get the data via:
echo $this->input->post('data_you_want_to_validate_together');

Right now, I have a custom function which will batch check every submission on my form to make sure it meets a set of rules. I am thinking that it may work to set up my form as an html array (data[]), retrieve it in code igniter, then use the CI callback_ validation function to make sure everything turns out okay. It seems complex, so I haven't yet entirely wrapped my head around it, but maybe this can get your wheels turning in the right direction.
EDIT:
$this->load->library('form_validation');
// If there is any posted data, then we should assign it to our $post_data array.
$post_data = $this->input->post('project_data');
if (empty($post_data)) {die('empty form');}
// Now, we are ready to validate the incoming data.
// We will send the data through a callback function which will check to make sure it is valid.
// If it is not valid, the callback function will trigger a codeigniter validation error.
// Let's temporarily remove any commas from the submission data to avoid delimiter confusion when sending it through the callback
$post_data = str_replace(",", "DELIMITEDCOMMA", $post_data);
$post_data_str = http_build_query($post_data);
$this->form_validation->set_rules("project_data[errors]", 'Errors', "required|callback__validate_project_data[$post_data_str]");
$this->form_validation->run();
Then, just write your custom validation function based on what it is that you need to validate.
function _validate_project_data($value, $request)
{
// A callback rule check is being attempted by the CI validator
// $value is the actual value of the submission, while $request is the key and value
$request = explode(",", $request);
$request = str_replace("DELIMITEDCOMMA", ",", $request);
// rename the keys in the request back to the original convention
parse_str($request[0], $request);
//var_dump($request);
// perform validation here and return true or false (valid or invalid)
}

Not entirely sure what you mean, as the fields would have to be checked individually whichever way you do it. Unless you're concatenating all the inputs and checking that? Maybe I've missed something there though.
Just go for client side: http://flowplayer.org/tools/demos/validator/index.html
Serverside: http://formigniter.org/
Hope this helps...

Related

Symfony2: doing form validation before the form is posted

Going to try my best to explain this...
In my app I have the need to display the validation errors on a form when the user loads the form initially. In short, they've entered data and saved it, but now the data has been checked and we've detect errors they need to correct before they can fully submit the form. (It's multi step form that can be filled out over multiple sessions...think big.)
Previously I was doing something like:
THIS DOESN'T WORK IN SYMFONY >=2.8.10 See this answer
$entity // passed in as param on action method
$form = $this->createForm(..., $entity);
$csrfToken = 'random_string'; // retrieved from FormConfigInterface
// perform the submit but don't clear missing
$form->submit(['_token' => $csrfToken], false);
This was working, but seems to have broken in Symfony 2.8.10+, but works in 2.8.9. In 2.8.10+ there are no validation errors (the form is considered valid).
I'm able to retrieve the validation errors in a ConstraintViolationListInterface, but I can't find a way to "merge" that with the form (which I think would be the prefered way). Since I couldn't, I tried the above which "fake" submits the form...which seems like a bad idea.
Is there a better/proper way?
(Note: the form is much more complicated and includes validation groups...but I'm not concerned about that or the error in 2.8.10+ at this point.)

In Drupal 7, how can I alter the contents of a submitted form before the values are validated?

I would like to do something roughly analogous (but not exactly identical) to the following: I want to create a Person content type, which has an SSN field. I would like to store the SSN field as an integer, but allow the user to input the number as 123-45-6789. This means that before validation triggers, stating that "123-45-6789" is invalid input, I would like to remove the dashes and treat this as an integer.
I've tried to use both a #value_callback function, as well as a non-default validation function. The problem then is that although I can force the value to be validated, the unchanged value is what is passed to the db for insertion, which fails. In example, this means that although I can force "123-45-6789" to be recognized by Drupal as "123456789", the database is still being passed "123-45-6789", which of course fails.
The one obvious solution would be altering this via client side javascript, before the value is even submitted to the webserver. I would strongly prefer to avoid this route.
Apologies if I've misunderstood but you should just be able to do something like this:
function my_validation_handler(&$form, &$form_state) {
if (passes_ssn_validation($form_state['values']['SSN'])) {
// Changing the value in $form_state here will carry on over to the submission function
$form_state['values']['SSN'] = convert_to_db_format($form_state['values']['SSN']);
}
else {
form_set_error('SSN', 'The SSN was invalid');
}
}
Then you'd attach that validation function using $form['#validate'][] = 'my_validation_handler' in either your form build or form_alter function.
Hope that helps
you should use hook_node_presave(). It allows you to change the values of different fields before they are inserted to the database. Here's the official documentation:
http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_node_presave/7
Hope this can help :)

PHP: What's a better way to process form data?

On my website, I have user accounts that are configurable with forms that allow users to update everything from first and last names to privacy settings. I use the following function to update the database with that input. (Note that the following code uses WordPress-specific features.)
function update_account() {
global $current_user; get_currentuserinfo();
require_once( ABSPATH . WPINC . '/registration.php' );
$uid = $current_user->ID;
// First Name
if(isset($_POST['first_name']) && $_POST['first_name'] <> $current_user->first_name) {
wp_update_user( array(
'ID' => $uid, 'first_name' => esc_attr($_POST['first_name'])
));
}
// ...and so on 43 more times...
}
This feels like the wrong way to process forms. This also looks like it will negatively impact server performance when there are multiple users and frequent updates, given that the if-then-else conditions for every field, even fields not on a particular page, force checking each field for input.
Moreover, since form data can be expected to remain relatively constant, I added the <> operator to prevent the function from updating fields where there has not been any change, but I suspect this also means that every field is still evaluated for change. To make matters worse, adding new fields -- there are already 44 fields in total -- is an unwieldy process.
What's a better way to process form data?
Keep an array of the fields you will be processing with this code, and iterate over it. This works if all your attributes are strings, for example. If you have different data types such as boolean flags to handle differently from the strings, you may wish to group them into their own array.
// All the fields you wish to process are in this array
$fields = array('first_name', 'last_name', 'others',...'others99');
// Loop over the array and process each field with the same block
foreach ($fields as $field) {
if(isset($_POST[$field]) && $_POST[$field] != $current_user->{$field}) {
wp_update_user( array(
'ID' => $uid, $field => esc_attr($_POST[$field])
));
}
}
There's a lot of things missing with your implementation. I don't know what kinds of data you're allowing the user to manipulate but most usually have some kind of requirements to be acceptable. Like not having certain characters, not being blank, etc. I don't see any validation occurring, so how do you handle values that might be undesirable? And what happens when you receive bad data? How do you inform the user of the bad data and prompt them to correct it?
If we abstract the situation a bit we can come up with generalizations and implement an appropriate solution.
Basically form fields [can] have a default value, a user specified value [on form review], validation requirements and validation errors [with messages]. A form is a collection of fields that upon form submit needs to be validated and if invalid, re-displayed to the user with instructive corrective prompts.
If we create a form class that encapsulates the above logic we can instantiate and use it to pass around our controller/views. Oops, I was just assuming you were using an Model/View/Controller type framework, and I'm not really familiar with wordPress so I don't know if that is exactly applicable. But the principle still applies. On the page where you both display or process the form, here's some pseudo logic how how it might look.
function update_account()
{
// initialize a new form class
$form = new UserAccountInfoForm();
// give the form to your view for rendering
$this->view->form = $form;
// check if form was posted [however your framework provides this check]
if(!Is_Post())
return $this->render('accountform.phtml');
// check if posted form data validates
if(!$form->isValid($_POST))
{
// if the form didn't validate re-display the form
// the view takes care of displaying errors, with the help of its
// copy of the $form object
return $this->render('accountform.phtml');
}
// form validated, so we can use the supplied values and update the db
$values = $form->getValues(); // returns an array of ['fieldname'=>'value']
// escape the values of the array
EscapeArrayValues($values);
// update db
wp_update_user($values);
// inform the user of successful update via flash message
$this->flashMessage('Successfully updated profile');
// go back to main profile page
$this->redirect('/profile');
That makes your controller relatively clean an easy to work with. The view gets some love and care to, utilizing the $form value to display the form correctly. Technically, you can implement a method in the form class to give you the form html, but for simplicity I'm just going to assume your form html is manually coded in accountform.phtml and it just uses $form to get field info
<form action='post'>
<label>first name</label> <input class='<?=$this->form->getElement('first_name')->hasError() ? "invalid":""?>' type='text' name='first_name' value="<?=$this->form->getElement('first_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('first_name')->getError()?></span><br/>
<label>last name</label> <input class='<?=$this->form->getElement('last_name')->hasError() ? "invalid":""?>' type='text' name='last_name' value="<?=$this->form->getElement('last_name')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('last_name')->getError()?></span><br/>
<label>other</label> <input class='<?=$this->form->getElement('other')->hasError() ? "invalid":""?>' type='text' name='other' value="<?=$this->form->getElement('other')->getValue()"/> <span class='errmsg'><?=$this->form->getElement('other')->getError()?></span><br/>
<input type='submit' value='submit'/>
</form>
Here the pseudo code relies on the form class method "getElement" which returns the field class instance for the specified field name (which would be created an initialized in the constructor of your form class). Then on the field class methods "hasError" and "getError" to check if the field validated correctly. If the form has not be submitted yet, then these return false and blank, but if the form was posted and invalid, then they will have been set appropriately in the validate method when it was called. Also "getValue" would return either the value supplied by the user when the form was submitted, or if the form has not been submitted, the default value as specified when the field class was instantiated and initialized.
Obviously this pseudo code is relying on a lot of magic that you'd have to implement if you roll your own solution--and it's certainly doable. However, at this point I'll direct you to the Zend Framework Zend_Form components. You can use zend framework components by themselves without having to utilize the entire framework and application structure too. You might also find similar form component solutions from other frameworks but I wouldn't know about those (we are a Zend Framework shop at my work place).
Hopefully this hasn't been too complicated, and you know where to go from here. Of course just ask if you need any clarification.

What is the 'correct' way to gather $_POST input from my form via CodeIgniter/PHP?

This is more of a theoretical question than a specific one.
I have a form set up with CodeIgniter's Form Validation class. I have some rules being run, for example:
$this->form_validation->set_rules('address_line_1', 'Address Line 1', 'required|xss_clean|trim');
I eventually want to put the address_line_1 data into my Database. This is where I'm a little confused. It seems there are several ways of fetching $_POST data from within CodeIgniter:
$address = $_POST['address_line_1'];
$address = $this->input->post('address_line_1');
$address = $this->form_validation->set_value('address_line_1');
$address = set_value('address_line_1);
So which way is the 'correct' way?
Whilst I'm sure several of these assumptions are wrong, I've been led to believe that...
$_POST is unsanitised by CodeIgniter's security (I'm confident about this one)
$this->input->post() will sanitise the data (to a certain extent), but won't have applied any Form Validation prepping rules
$this->form_validation->set_value() is the same as set_value(), but...
... set_value() is intended to re-populate form inputs via their value="" element.
Which of my assumptions are correct and which are wrong? And what is the way I should be pulling through $_POST data when I'm prepping it with Form Validation? The Form Validation documentation is ambiguous when it comes to this. None of the examples ever show it actually passing input data onto a model, for example.
Thanks!
Jack
They are all different, or they wouldn't all exist.
$_POST['foo'] is unprotected and raw output. BAD. Don't touch. etc.
$this->input->post('foo') escaped and XSSified input. Defaults to FALSE instead of erroring.
$this->form_validation->set_value() this will take the validated output, which may have been modified through the validation rules. For example, if you add "trim" as a validation rule, the validated content will be trimmed.
set_value() just an alias of the method above. People don't like to use $this in their views.
This is all in the documentation.

Drupal 6 Validation for Form Callback Function

I have a simple form with a select menu on the node display page. Is there an easy way to validate the form in my callback function? By validation I don't mean anything advanced, just to check that the values actually existed in the form array. For example, without ajax, if my select menu has 3 items and I add a 4th item and try to submit the form, drupal will give an error saying something similar to "an illegal choice was made, please contact the admin."
With ajax this 4th item you created would get saved into the database. So do I have to write validation like
if ($select_item > 0 && $select_item <= 3) {
//insert into db
}
Or is there an easier way that will check that the item actually existed in the form array? I'm hoping there is since without ajax, drupal will not submit the form if it was manipulated. Thanks.
EDIT:
So I basically need this in my callback function?
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form_build_id = $_POST['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
$form['#programmed'] = $form['#redirect'] = FALSE;
drupal_process_form($form_id, $form, $form_state);
To get $_POST['form_build_id'], I sent it as a data param, is that right? Where I use form_get_cache, looks like there is no data. Kind of lost now.
Since you're already using AJAX, why not just write a bit of jQuery to only allow form submission if the choice is within the list of legal choices? This can be done within the custom module it already looks like you're working on (using drupal_add_js()).
It is not especially 'easy', but the standard way to do it would be to use Drupals Forms API for the callback submission as well - that way, you'll get the same validation that would happen on a non js submit.
Take a look at Adding dynamic form elements using AHAH. While it does not match your scenario exactly (they rebuild the form on the callback to add new elements, not to save data), the explanation of the processing workflow is pretty helpful.
Then there are several modules that try to offer AJAX form submission in a generic way - you could check their code on how to do it (or maybe just use them ;)
Ajax submit (only has a dev version)
Ajax (has an 'official' release)
Finally, there are efforts to put better support this functionality into core in Drupal 7 - the related discussions might also help.

Categories