Codeigniter - Form validation converting post variables from Array to "Array" string - php

I am building an HTML form with a set of checkboxes for selecting multiple categories using this format:
<input type="checkbox" name="category[]" />
So, when I post and print_r($_POST) to view the variable and values I get:
Array
(
[27] => on
[28] => on
[29] => on
)
Once I run $this->form_validation->run(); the categories array becomes "Array" as a string. I believe I have narrowed it down to "prep_for_form" function in the system/libraries/Form_validation.php file, but it seems like the recursive function is working correctly.
Thank you in advance.

I figured it out. When using the $this->form_validation->set_rules() method, in the validation rules (third parameter) I set it to trim|required. I guess the trim function treats the actual Array like a string "Array" and trims the word. I simply removed the "trim" rule from my validation rules. e.g.
$this->form_validation->set_rules('category', 'categories', 'trim|required');
// when parsing an array (set of checkboxes, radio buttons, etc.)
// - remove the "trim" validation
$this->form_validation->set_rules('category', 'categories', 'required');
I hope others find this useful.

That solution did not work for me, but there is a fix listed here that did: http://ellislab.com/forums/viewthread/156497/

Related

What are nested parameters in http?

In the Laravel Docs on validation they speak of 'nested parameters':
If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
What would the HTML look like for this nesting? I googled around, and found nothing except things about form nesting. Also, the "dot" syntax, is this specific to Laravel?
The dot notation is for easily accessing array elements, and making their selectors more "fluent".
Validating author.name would be the equivalent of having checking the value of the input <input type="text" name="author[name]" />.
This makes having multi model forms or grouping related data much nicer =). You can then get all the data for that thing by doing something like $request->request('author'); and that would give you the collection/array of all the values submitted with author[*]. Laravel also uses it with its config accessors - so config.setting.parameter is the equivalent of config[setting][parameter]
Basically makes working with array data easier.
See https://github.com/glopezdetorre/dot-notation-access for some examples!
The Html form will look like Nothing More

Laravel Validation - How to check if a value exists in a given array?

So, okay i tried a lot of rules from validation docs but all give me same error saying
Array to string conversion
Here is how I add the array:
$this->validate($request,[
'employee' => 'required|in:'.$employee->pluck('id')->toArray(),
],[
'employee.in' => 'employee does not exists',
]);
Any hint on how to achieve this?
i created a custom validator but still passing array seems to be not possible
Implode the array as a string and join it on commas.
'employee' => 'required|in:'.$employee->implode('id', ', '),
This will make the correct comma separated string that the validator expects when making an in comparison.
Edit
This still works, but is not the Laravelesque way of doing it anymore. See the answer by #nielsiano.
Update: You are now able to use the Rule class instead of imploding values yourself as described in the correct answer. Simply do:
['someProperty' => ['required', Rule::in(['needed', 'stuff'])]];
As mentioned in the 'validating arrays' section in the documentation: https://laravel.com/docs/5.6/validation#validating-arrays

Nested input with L4's validator

Does anyone know how to validate nested input sets using the Laravel 4 validator?
I have a table with a set of line items, and each quantity field has the unique package id in square brackets in the name:
<input type="text" name="quantity[package_one]" />
<input type="text" name="quantity[package_two]" />
This results in a nested input array:
<?php
array(
'quantity' => array(
'package_one' => 3,
'package_two' => 12
)
);
Which is exactly what i want, but i'm unsure how to specify rules for these items using the validator class:
// Does not work :-(
Validator::make(Input::all(), array(
'quantity[package_one]' => 'numeric|required|min:1',
'quantity[package_two]' => 'numeric|required|min:1'
));
This does not seem to work, neither does nesting the rules under quantity. Obviously there are workarounds to this like building a custom array of input yourself before passing it to the validator etc, but what i'd like to know is:
is there a native, "Laravel" way of handling nested input like this?
Thanks in advance,
Dan.
The dirty way....
Controller
$input = Input::all();
$input = array_merge($input, $input['quantity']);
Validator::make(Input::all(), array(
'package_one' => 'numeric|required|min:1',
'package_two' => 'numeric|required|min:1'
));
Validator does not look into nested arrays. just bring that array to the outer one and you are done. (you can unset $input['quntity'] if you want after that)
loophole here is, it assumes that $input['quantity'] is present in the array. You need to validate this before putting into validation.
Works but not efficient.
You could make an extra Validator object just for the quantity input. It requires more code but i think it's more robust than merging in to one array

jquery .serialize() select multiple tag name for array is being encoded

I have a select multiple tag with a name city[]. The [] brackets are supposed to signify an array in the url query string for the PHP later.
I'm using jQuery .serialize() to get the form value to build a query string for an AJAX call. However, it looks like .serialize() is encoding the URL and not writing the brackets
I should get
index.php?city[]=METROPLOIS&city[]=GOTHAM
Instead I'm getting
index.php?city%5B%5D=METROPLOIS&city%5B%5D=GOTHAM
Is there a way to make it stop encoding for just the name? There may be some instances where the city name has a space, so I'll still need it to encode that.
I think you are just a bit confused since you may be unfamiliar with URL escaping.
But, this works perfectly in PHP. For instance, print_r($_GET) will output:
Array
(
[city] => Array
(
[0] => METROPLOIS
[1] => GOTHAM
)
)
Being city interpreted correctly as an array and containing the expected values. Since, city%5B%5D is a valid URL encoded string for city[].

drupal7: using form_set_value()

I am trying to update a value during the validate phase of a node-form, i.e. if the custom validation error is fired, just empty one of the fields.
for the last 30 hours I am trying to make sense of the drupal api, but I am giving up. I just do not seem to get the idea what the different values mean.
the function is: form_set_value($element, $value, &$form_state)
now i understand that the last value is simply the $form_state, that I am having through the validate function. but what about $element and $value?
I was trying a lot and apparently the desired value resides in $form['field_name']['und'][0]['value']['#value'] and only there.
but when I am trying form_set_value($form['field_name']['und'][0]['value']['#value'],'foo',$form_state) it raises
Recoverable fatal error: Argument 2 passed to drupal_array_set_nested_value() must be an array, string given, called in /includes/form.inc on line 2436 and defined in drupal_array_set_nested_value()
and when I am trying:
$newvalue = $form['field_name']['und'][0]['value'];
$newvalue['#value']='foo';
form_set_value($form['field_name']['und'][0]['value'],$newvalue,$form_state);
it raises:
Warning: mb_strlen() expects parameter 1 to be string, array given in drupal_strlen()
Thanks for any help!
Unless I'm really mis-understanding what you're trying to do this will work:
$form_state['values']['field_name']['und'][0]['value'] = '';
When the form is re-built after a validation error the values in $form_state['values'] are used to re-populate the fields in the form. So, if you reset the value in the $form_state['values'] array it will not be there when the form is shown with the validation errors.
After a lot of debugging, I finally managed to make this work. The trick lies inside $form['complete form']. but first things first, how does form_set_value() work and what does it do?
the form_set_value() function
as the docs suggested:
if you want to update the value of $form['elem1']['elem2'], which should be stored in $form_state['values']['elem1']['elem2'], you would set $element['#parents'] = array('elem1','elem2').
now what does that mean? in my case, I had a textfield called 'field_event_title', which is the name I gave it on creation. in $form, all fields have a sub-array in $form['field_name'], which is in my case $form['field_event_title']. this is where the submitted value also is stored. now since it is a textfield, drupal maintains both the language and the delta [question for editors: is this right?] of the inputted data. so in fact, the value is not stored in $form['field_name']['value'], but in $form['field_name']['und'][0]['value'] (['und']=language; [0]=delta). note that 'und' is the drupal key for the default language of the site, if it is, say, in german, then it would be 'de', however, in most cases it should be 'und'.
to actually change the value using form_set_value(), one is ought to invoke the function by writing:
form_set_value($form['field_name'],array('und' => array(0 => array('value' => 'foo'))),$form_state);
i.e. $element = $form['field_name'] $value=array('und' => array(0 => array('value' => 'foo')))
updating a form to repopulate it with different values than submitted (or clearing them)
but that did not work in my case since I wanted to clear fields once a custom validation error has been invoked. now one would suspect that the form repopulates itself using the values inside $form_state['values'] (which is actually the place where the values are stored, the actual place that gets updated when using form_set_value() and the place which generates the $form later.), but that is not the case: it uses the values inside $form_state['complete form'], which is a 'copy' of $form (notice that it is spelled 'complete form', with a space, not an underscore).
so using $form_state['complete form']['field_name']['und'][0]['value']['#value']='foo'; is what updates the values that actually repopulate the form on a validation error. (note: you can, as do I in my usecase, set it to =NULL to simply empty the field).
summary
now where is the difference between $form['field_name'] (e.g. updating through form_set_value()) and $form['complete form']? well, the former updates the actual value, which then gets stored inside the database, the latter is being used to repopulate a form when it failed a validation.

Categories