Getting data from dynamic form - multi-field row - php

Currently I am creating a form that has a option to add dynamically fields ( as rows with extra fields ). The generator is a table that just adds a into a bootstrap wrapper. As you can see on the image below. Everything is working smooth, but I am quite clueless about the post POST programming, cause for now the var_dump seems to be messy and I am not quite sure what solution would be the best a) form the data in jquery while sending the data to php or b) merge the post data to a user array. Over all the desired output would be (PHP)
array()
['user1'] =>
['role'] => 'something'
['can_edit'] = > 0
['can_read'] = > 1
['can_execute'] = > 1
['is_admin'] = > 0
Just wondering how to achieve that, give me some hints. Besides - As you see "on" represents the is_checked so it will be 1 if its 0 its not present at all - but that's not a problem.
The post var_dump
["user"]=>
array(4) {
[0]=>
string(5) "user1"
[1]=>
string(5) "user2"
[2]=>
string(5) "user3"
[3]=>
string(5) "user4"
}
["role"]=>
array(4) {
[0]=>
string(9) "something"
[1]=>
string(9) "something"
[2]=>
string(9) "something"
[3]=>
string(9) "something"
}
["can_edit"]=>
array(4) {
[0]=>
string(2) "on"
[1]=>
string(2) "on"
[2]=>
string(2) "on"
[3]=>
string(2) "on"
}
["can_read"]=>
array(2) {
[0]=>
string(2) "on"
[1]=>
string(2) "on"
}
["can_execute"]=>
array(2) {
[0]=>
string(2) "on"
[1]=>
string(2) "on"
}
["is_admin"]=>
array(1) {
[0]=>
string(2) "on"
}
My generator
$(".addCF").click(function(){
$("#customFields").append('<tr><td>'+sel[0].outerHTML+'</td><td><input class="form-control" type="text" name="role[]" /></td><td><input type="checkbox" class="mycheckbox" name="can_edit[]"></td><td><input type="checkbox" class="mycheckbox" name="can_read[]"></td><td><input type="checkbox" class="mycheckbox" name="can_execute[]"></td><td><input type="checkbox" class="mycheckbox" name="is_admin[]"></td><td>Remove</td></tr>');
$('.mycheckbox').iCheck({checkboxClass: 'icheckbox_square-blue',radioClass: 'iradio_square-blue'});
});

I'm assuming you're naming the inputs like name="user[]" ?
Usually I'll do it by adding a counter to the name field such as name="user_1" then name="user_2", etc and let the JS track that.
Then in the php I'll loop though like this:
$records = array();
foreach ($_POST as $key => $value)
{
if (substr($key, 0, 5) != 'user_') continue;
$row = substr($key, 5);
$user = $_POST['user_'.$row];
$role = $_POST['role_'.$row];
$can_edit = 0;
if (isset($_POST['can_edit_'.$row])) $can_edit = 1;
// ETC
// VALIDATION GOES HERE
// IF NO VALIDATION ERRORS:
$records[] = array('user' => $user, 'role' => $role, 'can_edit' = $can_edit;
}
javascript generator:
$(".addCF").click(function(){
count = $('#customFields tr').length + 1;
$("#customFields").append('<td>'+sel[0].outerHTML+'</td><td><input class="form-control" type="text" name="role'+count+'" /></td><td><input type="checkbox" class="mycheckbox" name="can_edit'+count+'"></td><td><input type="checkbox" class="mycheckbox" name="can_read'+count+'"></td><td><input type="checkbox" class="mycheckbox" name="can_execute'+count+'"></td><td><input type="checkbox" class="mycheckbox" name="is_admin'+count+'"></td><td>Remove</td></tr>');
$('.mycheckbox').iCheck({checkboxClass: 'icheckbox_square-blue',radioClass: 'iradio_square-blue'});
});

Related

Insert two arrays data to database

I'm getting two form datas as array .I want to insert those data in my table.
arrays
> var_dump($name);
array(3) { [0]=> string(5) "allen" [1]=> string(4) "dave" [2]=> string(3) "len" }
> var_dump($designation) ;
array(3) { [0]=> string(7) "analyst" [1]=> string(8) "designer" [2]=> string(2) "pm" }
below is my table insert query
foreach ($name as $list) {
$sig = new Names;
$sig->name =$list;
$sig->designation =?;
$sig->festival = $id;
$sig->save();
}
how to insert desgination array ? pls advice

Compare associative array keys and values for checkbox

I have a web form with checkboxes for Event Spaces.
The checkbox values are grabbed from one table in my database "facility_event_charges":
Let's say I check 5 and 6, "Audio Visual Equipment" and "Audio Visual Technician" and submit my form.
This will save the id(s) to a separate table that I have for that "Event Space"
Let's say my "Event Space" has an ID of 63. The lookup table now has two entries for my id since I checked 2 of the checkboxes:
All is good and saved.
Now, let's say I need to actually edit the charges associated with this space.
When I click edit, my webform renders the form fields BUT the checkboxes are empty!! Why? Because it is grabbing the data from my "facility_event_charges" table.
I need to compare this table data (array) with the data saved in my lookup table (array) to figure out which values are in common and render a check in those checkboxes.
Desired result in my edit space webform would have those checked
My checkbox "charges" array:
array(6) {
[1]=> string(9) "Officials"
[2]=> string(6) "Ushers"
[3]=> string(19) "Additional Staffing"
[4]=> string(16) "Special Lighting"
[5]=> string(22) "Audio Visual Equipment"
[6]=> string(23) "Audio Visual Technician"
}
--
I can also generate the charges in this:
array(6) {
[0]=> array(1) { ["FacilityEventCharge"]=> array(2) { ["id"]=> string(1) "1" ["type"]=> string(9) "Officials" } }
[1]=> array(1) { ["FacilityEventCharge"]=> array(2) { ["id"]=> string(1) "2" ["type"]=> string(6) "Ushers" } }
[2]=> array(1) { ["FacilityEventCharge"]=> array(2) { ["id"]=> string(1) "3" ["type"]=> string(19) "Additional Staffing" } }
[3]=> array(1) { ["FacilityEventCharge"]=> array(2) { ["id"]=> string(1) "4" ["type"]=> string(16) "Special Lighting" } }
[4]=> array(1) { ["FacilityEventCharge"]=> array(2) { ["id"]=> string(1) "5" ["type"]=> string(22) "Audio Visual Equipment" } }
[5]=> array(1) { ["FacilityEventCharge"]=> array(2) { ["id"]=> string(1) "6" ["type"]=> string(23) "Audio Visual Technician" } } }
My lookup table array:
array(2) {
[0]=> array(1) { ["EventCharge"]=> array(1) { ["facility_event_charges_id"]=> string(1) "5" } }
[1]=> array(1) { ["EventCharge"]=> array(1) { ["facility_event_charges_id"]=> string(1) "6" } }
}
--
I've been unsuccessful in my attempts - tried php array_intersect
array_intersect_assoc
array_map('array_diff_assoc')
I need to loop through the checkbox charges array and find a match from the lookup table array, when it matches, mark the checkbox "checked".
Anyone have any working examples I could test out?
The checkbox charges array key is what would need to match the "facility_event_charges_id"
As per you array given above you can compare like this
for example Lets take $charge array as
array(6) {
[1]=> string(9) "Officials"
[2]=> string(6) "Ushers"
[3]=> string(19) "Additional Staffing"
[4]=> string(16) "Special Lighting"
[5]=> string(22) "Audio Visual Equipment"
[6]=> string(23) "Audio Visual Technician"
}
take $lookup array as
array(2) {
[0]=> array(1) { ["EventCharge"]=> array(1) { ["facility_event_charges_id"]=> string(1) "5" } }
[1]=> array(1) { ["EventCharge"]=> array(1) { ["facility_event_charges_id"]=> string(1) "6" } }
}
You can compare both array like below
$charges = array(
1 => "Officials",
2 => "Ushers",
3 => "Additional Staffing",
4 => "Special Lighting",
5 => "Audio Visual Equipment",
6 => "Audio Visual Technician"
);
$lookup = array(
array("EventCharge" => array(
"facility_event_charges_id" => "5"
)
), array(
"EventCharge" => array(
"facility_event_charges_id" => "6"
)
)
);
$lookup = array_column(array_column($lookup, 'EventCharge'), 'facility_event_charges_id');
foreach ($charges as $key => $value) {
echo '<input type="checkbox" name="charges" value="' . $key . '" '.(in_array($key, $lookup)?"checked":"").'>';
echo '<label>'.$value.'<label>';
}
Edit
If array_column() is not supported than you can create array using loop like below and test
$arr=array();
foreach ($lookup as $key => $value) {
foreach ($value as $k => $v) {
$arr[]=$v['facility_event_charges_id'];
}
}
foreach ($charges as $key => $value) {
echo '<input type="checkbox" name="charges" value="' . $key . '" '.(in_array($key, $arr)?"checked":"").'>';
echo '<label>'.$value.'<label>';
}
This works...
But it will change based on how exactly you end up building the arrays... but that should only require a change in the if-then statement and possibly a change in the value of i (the index variable).
<html>
<head></head>
<body>
<form>
<?php
// assume you build this based on a sql query
// you don't need to use the primary key for the
// array index
$charges[0]="Officials";
$charges[1]="Ushers";
$charges[2]="Additional Staffing";
$charges[3]="Special Lighting";
$charges[4]="AV Equipment";
$charges[5]="AV Technician";
// your array of eventcharges
// select facility_event_charges_id from tbl where facility_event_spaces_id='63'
// loop thru the result of teh query make a simple array of your evencharge ids
// gonna hardcode mine out of laziness
// since php is typeless we can use strings to compare to ints
// directly as long as we use == and not ===
// and in_array() (used below) goes with loose comparison too
$ec[]="4";
$ec[]="5";
// now we have an array of our descriptions
// and an array of the already selected choices
// from the db data
for($i=0;$i<count($charges);$i++){
print('<input type="checkbox" name="charges" value="'.$i.'" ');
if(in_array($i,$ec)){
print("checked");
}
print(" > ".$charges[$i]."<br />");
}
?>
</form>
</body></html>
Hi you can use following code.i assumed that you have got $arr=array('5','6'); from database.so you can us as follows
<?php
$arr=array('5'=>'Audio Visual Equipment','6'=>'Audio Visual Technician');
$arr=array_keys($arr);//if you have associated array
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="ISO-8859-1">
</head>
<body>
<input type="checkbox" name="charges" value="1" <?=in_array('1', $arr)?'checked=true':''?>> Officials<br>
<input type="checkbox" name="charges" value="2" <?=in_array('2', $arr)?'checked=true':''?>> Ushers<br>
<input type="checkbox" name="charges" value="3" <?=in_array('3', $arr)?'checked=true':''?>> Additional Staffing <br>
<input type="checkbox" name="charges" value="4" <?=in_array('4', $arr)?'checked=true':''?>> Special Lighting <br>
<input type="checkbox" name="charges" value="5" <?=in_array('5', $arr)?'checked=true':''?>> Audio Visual Equipment<br>
<input type="checkbox" name="charges" value="6" <?=in_array('6', $arr)?'checked=true':''?>> Audio Visual Technician<br>
</body>
</html>

Adding user's choices to test results

This is a little tricky to explain, so bear with me...
I've put together a database-driven test script that works pretty nicely. After a user selects their answers and pushes a submit button, they're forwarded to a page (grade.php) that displays their score.
Beneath the score is a copy of the test they just took, with the correct answers highlighted. I would simply like to modify it so that the answers users chose are also highlighted.
For example, if a user chose answer A, and that's the correct answer, then it might have a yellow background (indicating it's the correct answer) plus a gold star (indicating a user chose that correct answer). If a user chose B, then it might have a black background (indicating it's an incorrect choice), plus it might have an image depicting a checkmark, indicating that the user chose that incorrect answer.
Let's start with the form at the bottom of the test page:
<form action="grade.php" method="post" id="quiz">
<input type="hidden" name="PreviousURL" id="url" />
<input type="hidden" name="grade" value="<?php echo $grade; ?>" />
<input type="hidden" name="user_token" value="<?php echo isset($_POST['user_token']) ? $_POST['user_token'] : '' ; ?>" />
<input type="submit" value="Submit Quiz" />
</form>
After clicking submit, we're forwarded to grade.php, which has a switch containing answer keys for various tests. In this example, we took a ten-question quiz identified by its URL - px-intro-4. Here's the answer key:
$answers = array(1 => array('D'),
2 => array('A'),
3 => array('C'),
4 => array('A'),
5 => array('Libya'),
6 => array('B'),
7 => array('B'),
8 => array('B'),
9 => array('C', 'D'),
10 => array('D'));
$total = count($answers);
Most are multiple choice questions, where users select the one best answer. In this example, they have to type in an answer for #5, and they have to select TWO options (checkboxes) for #9.
If they get every answer correct, echoing var_dump($_POST); displays the following:
array(13) {
["q1"]=> array(1) { [0]=> string(1) "D" }
["q2"]=> array(1) { [0]=> string(1) "A" }
["q3"]=> array(1) { [0]=> string(1) "C" }
["q4"]=> array(1) { [0]=> string(1) "A" }
["q5"]=> array(1) { [0]=> string(5) "Libya" }
["q6"]=> array(1) { [0]=> string(1) "B" }
["q7"]=> array(1) { [0]=> string(1) "B" }
["q8"]=> array(1) { [0]=> string(1) "B" }
["q9"]=> array(2) { [0]=> string(1) "C" [1]=> string(1) "D" }
["q10"]=> array(1) { [0]=> string(1) "D" }
["PreviousURL"]=> string(25) "http://g1/test/px-intro-4"
["grade"]=> string(147) "
}
If they take the test again and miss #9 and don't answer #10 at all, the array changes to this:
array(12) {
["q1"]=> array(1) { [0]=> string(1) "D" }
["q2"]=> array(1) { [0]=> string(1) "A" }
["q3"]=> array(1) { [0]=> string(1) "C" }
["q4"]=> array(1) { [0]=> string(1) "A" }
["q5"]=> array(1) { [0]=> string(5) "Libya" }
["q6"]=> array(1) { [0]=> string(1) "B" }
["q7"]=> array(1) { [0]=> string(1) "B" }
["q8"]=> array(1) { [0]=> string(1) "B" }
["q9"]=> array(2) { [0]=> string(1) "B" [1]=> string(1) "D" }
["PreviousURL"]=> string(25) "http://g1/test/px-intro-4"
["grade"]=> string(147) "
}
To make it more clear, imagine the following text on the results page (grade.php):
Where do penguins live?
A. Africa
B. Antarctica (yellow background, indicating it's the correct answer + a gold star indicating the user chose this correct answer)
C. France
D. California
My page already displays correct and incorrect answers. Can anyone tell me how to superimpose the USER's CHOICES? I'll probably have to jump through a few hoops to make this work, but if you can just point me in the right direction, then I can play with it and maybe ask some more focused questions.
I should mention that I have a little experience with jQuery, though I'm working primarily with PHP - just in case there's a jQuery solution.

Magento attribute dropdown with first empty value

I want to show one dropdown with the values from product attribute. But always is showing the first position empty. I have 2 values but I don't know why the array have 3 positions
<?php
$options = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'tipo_paquete')->getSource()->getAllOptions();
var_dump($options);
?>
<select id="tipo_paquete" class="required select" name="tipo_paquete">
<option value=""><?php echo $helper->__('--Please Select--')?></option>
<?php
foreach ($options as $option)
{
echo "<option value='".$option['value']."'>". $option['label'] ."</option>";
}
?>
</select>
This code show the select like this:
And the var_dump show this:
array(3) { [0]=> array(2) { ["label"]=> string(0) "" ["value"]=> string(0) "" } [1]=> array(2) { ["value"]=> string(1) "8" ["label"]=> string(15) "Caja de cartón" } [2]=> array(2) { ["value"]=> string(1) "7" ["label"]=> string(14) "Caja de madera" } }
I don't know why I have 3 positions, I only saved 2 options. I tested with other attributes with the same problem.
I've found the solution here. getAllOptions can recieve two parameters:
array getAllOptions ([bool $withEmpty = true], [bool $defaultValues = false])
The $withEmpty adds an empty option to array
Just pass false to getAllOptions().
$options = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'tipo_paquete')->getSource()->getAllOptions(false);

filter data from an array - php

I have an array with the friends data including their name, id, gender. I want to extract the data from array which have opposite gender.
For example -
My gender is "Male"
Returned data -
[118]=> object(stdClass)#121 (3) {
["name"]=> string(9) "Rawa Su"
["gender"]=> string(4) "male"
["id"]=> string(15) "1000019100"
}
[119]=> object(stdClass)#122 (3) {
["name"]=> string(11) "Anil Gaj"
["gender"]=> string(4) "male"
["id"]=> string(15) "1000034656"
}
[120]=> object(stdClass)#123 (3) {
["name"]=> string(13) "Ankur Tri"
["gender"]=> string(4) "male"
["id"]=> string(15) "1000022271"
}
[121]=> object(stdClass)#124 (3) {
["name"]=> string(13) "Chuck Ell"
["gender"]=> string(4) "male"
["id"]=> string(15) "10000185038"
}
[122]=> object(stdClass)#125 (3) {
["name"]=> string(15) "Madhuri Tat"
["gender"]=> string(6) "female"
["id"]=> string(15) "1000880932"
}
Now i want to randomly fetch the data which have gender = female. I don't have any clue how this can be done. Any help would be appreciated. Thank you.
Okay lets say your array with all of the data is named $data:
$res = array();
foreach($data as $person) {
if(strcasecmp($person['gender'], 'female') == 0)
$res[] = $person;
}
Now you have a new array called $res which contains all females.
Nevertheless, i would filter the raw data during the sql fetch from the database,
this should be the same effort and give more performance in a long time view.
If you now want to have one of the females randomly, do something like this:
$number_of_persons = count($res);
$random_female = $res[rand(0, $number_of_persons-1)];
Why -1?
Arrays start at index 0, so you need a -1 at the total amount of persons.

Categories