Yii chekboxes breaking array of HTML forms - php

I have an array of forms for a list of accessories defined, in a simpler than existing form, like so:
echo CHtml::activeCheckBox($accessory, 'bidirectional[]', array('checked'=>$accessory->bidirectional));
I do the form building this way so that I can dynamically add new rows via jQuery without having to fiddle with index positions within all the elements.
The problem I am getting is that activeCheckBox produces two fields for the sake of setting 0 in the active record. This causes problems when I come to rebuild the form, due to two entries for this element I actually convert:
array(9) { ["bidirectional"]=> array(2) { [0]=> string(1) "0" [1]=> string(1) "1" } }
To the latter entry having it owns row and so breaking all my programming.
Is there anyway to do dynamic indexes for lists of forms in Yii easily or do I have to go back to using static indexes?

By default, yii activeCheckBox generates hidden input, so when submitting form value is always set. In your case hidden inputs breaks indexes.
To keep dynamic indexes hidden inputs should be removed. Drawback of this is that you no longer have "unchecked" value. To disable uncheck value, simply set uncheckValue to null:
echo CHtml::activeCheckBox($accessory, 'bidirectional[]', array(
'checked'=>$accessory->bidirectional,
'uncheckValue' => null
));

Related

Sending a POST array and memory leak

When sending an HTTP POST array of text data, for example from a web page with an HTML form and text fields, if we use as the name property of the fields the following array url_alias[id] with id being a positive integer, we receive with PHP:
[url_alias] => Array
(
[2644] => url-of-product-ref-123
[1] => url-of-product-ref-224
)
how will the server (Apache Linux, for example) handle the POST data? Will it internally prepare an array with 2645 indexes, with a null pointer to all indexes except the index: 1 and the index: 2644, or will it do in other, optimized way? Is the format above correct in terms of efficiency - it is very comfortable for PHP programming, but I am afraid of memory leakages or something.
From PHP manual:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
In your example it holds only two keys with one value assigned to each.
The manual has examples on how arrays in PHP behave. For example, if you set up the following array:
$array = array(
"a",
"b",
6 => "c",
"d",
);
They keys assigned will be 0, 1, 6 and 7:
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[6]=>
string(1) "c"
[7]=>
string(1) "d"
}
Please read the manual to learn more.
UPDATE
You are also asking how arrays are sent over HTTP. They (arrays) are not. According to W3C specification defined here:
The form data set is then encoded according to the content type specified by the enctype attribute of the FORM element.
Each enctype has it's own rules too long and extensive to be listed here. Read it there if you wish. The thing is, when PHP receives the encoded data, it automatically decodes indexed form variable names.
So, to wrap it up, the form data is encoded, sent to PHP and the decoding process is on PHP side.

PHP/mySQL get all column names and create list

I'm using this to define the valid keys that can be used to perform a search on my front end:
$validKeys = array('gender','marital_status', 'age');
The rest of my code works great in that it only accepts keys sent to it in an AJAX call that are in this array.
However, I want to be able to make this list ('gender','marital_status', 'age') dynamic. That is, I'd like to include all of the columns from my table in here so that every column is essentially a valid key. I have about 10-15 depending on the table and I'd rather not hard-code it into each PHP file.
How would I go about getting all the column names in my table and arranging them into this variable? So, I need to get all the names, put them in single quotes and comma separate. Unless there's a way to get them in a proper array and skip the array part of defining the $validkeys variable.
If I var_dump $validKeys, I get this:
array(5) {
[0]=>
string(6) "gender"
[1]=>
string(14) "marital_status"
[2]=>
string(3) "age"
[3]=>
string(7) "anglers"
[4]=>
string(8) "baseball"
}
Any direction would be appreciated.
EDIT: Should have been more explicit that I am using PDO.
you can try with mysqli's fetch_fields-function.
$finfo = $result->fetch_fields();
Documentation: http://php.net/manual/de/mysqli-result.fetch-fields.php
Run a query using the DESCRIBE syntax. That will return all columns to you which you can then place in the array.
DESCRIBE `table_name`;
Another option is SHOW COLUMNS. Either will work for your requirements.
I should have been a bit more explicit that I am using PDO, so Jay's answer above pointed me in the right direction and I found this answer that gave me the details: https://stackoverflow.com/a/7091984/989722
The full code snippet based on my question looks like this:
$q = $dbh->prepare("DESCRIBE full_db2");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
$validKeys = $table_fields;

form_multiselect gives only one option

Sorry, but this is kind a homework question...
I have to make a webpage with codeigniter and I have to use multiple select component.
So my code.
Part in *view.php file:
<br>Keywords:<br>
<?php echo form_multiselect('keywords', $keys); ?>
Also there is submit button, and after it pressed I take POST data. For debugging tried:
var_dump($_POST['keywords']);
This always shows, that there is only one option selected, for example, string(1) "2"
Can someone advice how should I modify my code to get all selected items.
Please try:
<?php echo form_multiselect('keywords[]', $keys); ?>
A multiselect form field must have a name with array notation.
You would expect codeignitors function to accommodate this, but it doesnt (well not when i last used CI in 2010)
From the Codeigniter documentation:
form_multiselect()
Lets you create a standard multiselect field. The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value or values you wish to be selected. The parameter usage is identical to using form_dropdown() above, except of course that the name of the field will need to use POST array syntax, e.g. foo[].
The last sentence states you need to use POST array syntax, so the name of the select should be, in your case
name="keywords[]"

filtering out nonvalues with php explode()

I have an array with a field of type string in php.
I'm using it to keep track of history. everytime a user performs a specified action the user id is added to the string. I'm using the RedBean ORM, so to declare the field varchar using mysql I have initialized it as:
$history_field="0 ,";
but when I perform:
$history_array= explode(',', $history_field);
I get:
array(2) { [0]=> string(2) "0 " [1]=> string(0) "" }
There should be one element in the array - namely '0' , I would have thought. Is this a bug?
how can I fix this to get my expected result. Thank you.
As per the documentation (and the comments) this is expected behavior, you can use this to filter out the empty values:
array_filter(explode(',', $history_field), 'strlen');

$_GET Breaks XML

I'm using the SimpleViewer flash image gallery on a site, and it uses an XML file for information about the images it displays.
For the site, I need to dynamically generate the XML, so I'm using a PHP file with a text/xml Content-type declared. However, for some reason when I access one of the GET variables in the $_GET array SimpleViewer tells me that there are no images in the gallery, even though when I view the source it looks the exact same and is well-formed.
Here's the code:
$photos = array(
"1" => array("house1_1.JPG")
);
foreach($photos[$_GET["hid"]] as $p){
echo '';
}
If I replace $_GET["hid"] with "1" then it works fine, but when I make the reference to $_GET it returns the error.
Is there some reason as to why accessing a GET variable would cause scripts linking to the XML (the SimpleViewer flash) to malfunction, and is there a way to get around this?
*Note: The "hid" GET variable is 100% sure set to "1", and there is no PHP error.
Also, the output looks exactly the same for when I use $_GET["hid"] versus "1", the only difference is the SimpleViewer script refuses to see that the images are there.
Also, the stuff in the empty quotes is some XML, but I don't know how to get it to appear in the tags...
Var dump of $photos and $_GET, respectively:
array(1) {
[1]=>
array(1) {
[0]=>
string(12) "house1_1.JPG"
}
}
array(1) {
["hid"]=>
string(1) "1"
}
I would first check and make sure $_GET["hid"] is returning "1". If it's possible that it is not returning "1" then it should throw an error accessing a bad index of $photos.
Is the $_GET hid variable set in your request? If not this will trigger a PHP warning.
var_dump($_GET['hid']); to see the value of the $_GET variable and ensure it as you expect.
Also please ensure that you have error reporting set to at least E_ALL and display errors is set to yes/true to make your debugging easier.
I think you're probably having an issue with the difference between "1" and 1. When you use a get with something like ?hid=1, it's not coming through as a string, that's being converted to a number, whereas your actual array is using the string "1" as the key.
Either change your key to 1 instead of "1" or cast the hid to string.
Issue was never resolved -- I ended up having to just move on and go for a longer and less elegant solution. Oh well.

Categories