need some help figuring out how to approach this validation - php

I am using codeigniter for my form validation. I have two select fields named parent_male and parent_female. I would like to have a validation callback to check both the parent_male and parent_female in my database to see if it exists. I already have a previous callback function that does just that, but with only one field. I would like to check the two field values against the database, except I am not sure how to approach this idea. Any help/ideas are greatly appreciate! Thank you.
-Rich

You can define your callback as:
function isparent($parent) {
$result = FALSE;
/* do your stuff to check $parent is a valid parent and then ... */
return $result;
}
and the rules can be set as
$this->form_validation->set_rules('parent_male', 'Male parent', 'callback_isparent');
$this->form_validation->set_rules('parent_female', 'Female parent', 'callback_isparent');
In that way you use the same callback for both fields.

Related

What is elegant solution for a PHP function with a lot of parameters?

I need to create a function that would insert user data into a "medical_records" table that has about 30 fields.
So the "classic" solution is writing something like:
function insert_medical_records($param1, $param2,..., $param30) {
// code here
}
But of coarse, such code writing is prone to errors and not elegant at all.
I thought of better solution like creating an array of parameters and passing its values to the function, but I don't quite know a valid syntax for that.
Or maybe there is a better solution then this altogether?
Thank you!
Since php has a soft type control, you can just give your function one input parameter. That parameter will be an array or an object.
In case of an array:
function insert_medical_records($input_array) {
// Here you can use $input_array['param1'], $input_array['param2'],
}
Before calling the function, you need to populate the array, something like:
$input_array['param1'] = "your param 1 value";
$input_array['param2'] = array('a' => 1, 'b' => 2);
insert_medical_records($input_array);
I would also suggest you to check the content of the input variable of the function:
function insert_medical_records($input_array) {
if (!isset($input_array['param1'])) {
// manage your error
return;
}
// Everything is ok. Do your stuff here...
}
Instead of isset, you should also consider using empty, is_array or array_key_exists. This it's up to your specific situation.
The solution using Object instead of Array is really similar. You define attributes such as $input_object->param1.
How about:
class MedicalRecords {
/* code here */
}
function insert_medical_records(MedicalRecords $mr) {
/* more code here */
}
and now you can add logic to do thing like validation on the records to the object itself and better seperate your code's concerns along more logical lines.

Required dynamic Zend_Form_Element_Multiselect

I've got a <select multiple> populated on start up with some values, but where additional options are added via Javascript. However I'd like now to validate this element, that at least one of the options within has been selected.
I'm using Zend_Form_Element_Multiselect to perform the validation:
$tags = new Zend_Form_Element_Multiselect('cms_tags');
$tags->setRegisterInArrayValidator(false)->setRequired(true);
However, of course, this is not working. How can I do something as simple as checking for not emptiness of the cms_tags array without resorting to overloading isValid function?
PS. Validate_Not_Empty is not working as well.
Fortunately, the solution to my question is my code. Unfortunately, Zend, at least to me, has a bug - the problem with my data was an empty value that appeared at the end of the values array, so cms_tags[]=5, cms_tags[]= was considered invalid for this kind of validator. If this a valid behavior, or not, I'll leave it to Zend folks, but this at least answers my issues.
Try something like this:
public function isValid($data) {
$etat_valid = parent::isValid($data);
if(isset($data['cms_tags'])){
// Add your validators
// for example:
if("" == $data['cms_tags']){
$this->getElement('cms_tags')->addErrors(array('This value is required and can not be empty'));
$etat_valid = false;
}
}
return $etat_valid;
}

Zend Framework 2 - Removed form element causes validation to fail

I use a certain form in several places. In one of them I need to ignore a form element which I set programmatically after the validation.
Because it's just an exception I don't want to create a new form. So I thought, I just remove this element in the controller like:
$myForm->remove('myElement');
The problem is that the form now won't validate. I don't get any errors but the $myForm->isValid() just returns an empty value.
Any ideas what I might be doing wrong?
Ok, finally I found a solution! You can define a ValidationGroup which allows you to set the attributes you'd like to validate. The others are not validated:
$form->setValidationGroup('name', 'email', 'subject', 'message');
$form->setData($data);
if ($form->isValid()) {
...
The first thing I thought about was to remove the validator from your myElement's ValidatorChain. You could get it within the controller with:
$form->getInputFilter()->get( 'myElement' )->getValidatorChain()
It seems like you can't remove from the ValidatorChain, just add. Check this post. Matthew Weier O'Phinney, from Zend, explains why it can't be done and a possible solution for your scenario.
The way I solve this problem, is checking the 'remove condition' when I create the validator in the FormFilter class. If you use annotations I think it doesn't works for you, so Matthew suggestions is the one you should use.
Or you could try the one in this post from #Stoyan Dimov: define two forms, a kind of BasicForm and ExtendedForm. The first one have all the common form elements, the second one is an extended one of the other with the rest of fields. Depending on your condition you could use one or another.
In class ValidatorChain implements Countable, ValidatorInterface, add a new method:
public function remove($name){
foreach ($this->validators as $key => $element) {
$validator = $element['instance'];
if($validator instanceof $name){
unset($this->validators[$key]);
break;
}
}
}
Use like this:
$form->getInputFilter()->get("xxxxx")->getValidatorChain()->remove('xxxxxx');
There must be a validator defined for this particular element that you are trying to remove.
In your controller where you are adding new elements to form, there must be addValidator calling like:
$element->addValidator('alnum');
That is actually causing validation to be failed. So you have removed the element from form but you still have validation defined on that element to be checked.
If you are not able to find this validation adding function in controller, try to see if it has been defined through config file.
You can read further about form validation in zf here: http://framework.zend.com/manual/1.12/en/zend.form.elements.html
I remove the element with:
$form->get('product')->remove('version');
When I post the form I disable the validator on this element with :
$form->getInputFilter()->get('product')->get('version')->setRequired(FALSE);

How do you restore the values of the form in case if validation failed (in Kohana 3)

There is a sample in the bottom of the official documentation http://kohanaframework.org/3.2/guide/kohana/security/validation
But obviously it wont work at the request as long as $post['username'] in View is used but the $post array is empty on first request.
So how do you restore the values in this case? Any general solution?
PS: yes, I do understand I could do isset($post['username']) ? $post['username'] : ''; but it is just annoying
I use the model to display the data in the form. That way the initial form value is the initial value in the model.
I then update the model data with POST data in the controller, if there are validation errors, the model data will contain the POST data. This means I don't have to put any conditional logic in the view, and I just do: Form::input('name', $model->name)
Here's a more detailed explanation of this approach: Kohana ORM and Validation, having problems
I use Arr::get function:
echo Form::input('name', Arr::get($post, 'name'))
I was just looking at the old documentation on Building and Validating a Form.
You can see from the sample code that first you need to initialize an array with the form field names as the key and set the value to an empty string. And if there's an error, fill in the values of each element. In the views, you can simply call Form::input() normally without any if statement or some sort.
I guess Kohana has already been built this way from the start. And it doesn't seem to change. You'll probably just need to do the same thing.

CodeIgniter Callback Problem

I have an application that allows users to create forms and assign validation to each field (think http://www.phpform.org/ or http://wufoo.com/). I can easily get each field’s name and label from the database, as well as the array of associated validation rules.
Say, for example, I wanted to apply a blanket rule of “required” for all of the user defined forms, I would do something like this:
foreach($fields as $field)
{
$this->form_validation->set_rules($field[‘name’], $field[‘label’], ‘required’);
}
Now, the problem is that I need to replace “required” with a callback. In order for the callback to work, I’m going to need the field’s id (so the callback can use this id to lookup the field's associated validation rules). How do I get this id value to the callback function?
foreach($fields as $field)
{
$this->form_validation->set_rules($field[‘name’], $field[‘label’], "callback__example[$field[‘id‘]]");
}
// your callback... see ~line 589 of Form_validation library
public function _example($str,$id)
{
// do something to $str using $id, return bool
}

Categories