Fill the checkboxes from an array in PHP - php

Everyone
My question is so clear I think:
I have an array of checkboxes in HTML
<input type="checkbox" name="gruplar[]" value="<?=$deptId?>">
It takes "value" values from database ID's e.g. 1,4,5
I can get these values in an array variable named $divided[]. For example 1,4,5 selected and the array is: $divided[0]=1,$divided[1]=4,$divided[2]=5,
When I need to update the record of checkbox list, I want to get this checkbox list selected with these array values.
Check the checkbox which has "value" of "1", "4" and "5" according to
the elements of the array.
How can I do that in HTML mixed PHP context?

<input type="checkbox" name="gruplar[]" value="<?=$deptId?>"<?=(in_array($deptId,$divided))?' checked="checked":''?> />
This checks if the value of the checkbox (as given by $deptId, which I'm assuming is what you meant as you're echoing it for the value attribute) is in the array $divided. If it is, it echos markup to make the checkbox checked when it is rendered by the browser.

<?php
$checked = array(1, 4, 5);
foreach ($all as $id) // $all is all checkboxes
{
sprintf('<input type="checkbox" name="gruplar[]" value="%d" %s>', $id, in_array($id, $checked) ? 'checked="checked"' : '');
}
?>
Also, it's better to build meta array like this
array(
//(int) id => (bool) checked
1 => true,
2 => false,
...
);
Then do:
foreach ($meta as $id => $checked)
{
sprintf('<input type="checkbox" name="gruplar[]" value="%d" %s>', $id, $checked ? 'checked="checked"' : '');
}

For Update ur Checkbox Field will display the PHP if else condition for comparing two variables for mapping
if(in_array($depid,$divided)){
$checked = "checked='checked'";
}else{
$checked = "";
}
<input type="checkbox" name="gruplar[]" value="<?=$deptId?>" <?=$checked; ?>/>

Related

Show only the specific indexed array

How can I show only the specific index? For example, here's my UI.
As you can see in the picture I have 3 checkboxes and 3 textboxes with array value.
Let's say these are the name of the element.
<input type="checkbox" name="check[]">
<input type="text" name="textbox[]">
Then print the array:
$check = $_POST['check'];
$total_rec = $_POST['textbox'];
echo 'Check Array<br>';
print_r($check);
echo '<br<br><br><br>';
echo 'TextBox Array<br>';
print_r($textbox);
Result:
Check Array
Array ( [0] => 2 )
TextBox Array
Array ( [0] => [1] => 2 [2] => )
As you can see in textbox array all index showed, all I want is to show only the specific index with value and that is the 1 => 2 only.
use empty(), return true if contain value, example :
//iterate each $total_rec's member
foreach($total_rec as each){
//if $each not empty, do something
if(!empty($each)){
echo $each;
}
}
You are using $total_rec for post values of both checkbox and text. You can filter the array of text input like this:
$total_rec_text = $_POST['textbox'];
$total_rec_text = array_filter($total_rec_text, function($arr){
return !empty($arr) ? true : false;
});
You need to loop over $_POST array and check if checkbox is checked.
If checked, then only, get/print value.
Also, in HTML, you need to add specific counters to both checboxes and
textboxes.
As only checked checboxes get posted and texboxes get posted by
default.
<input type="checkbox" name="check[0]">
<input type="text" name="textbox[0]">
<input type="checkbox" name="check[1]">
<input type="text" name="textbox[1]">
<input type="checkbox" name="check[2]">
<input type="text" name="textbox[2]">
if (isset($_POST['check'])) {
foreach ($_POST['check'] as $idx => $value) {
echo "<br/>" . $_POST['check'][$idx] . ' ' . $_POST['textbox'][$idx];
}
}

Retrieve Checkbox Value that has been stored on DB

I've been stored my checkbox value into DB using this code
$request->merge([
'revisi_dokumen' => implode(',', (array) $request->get('revisi_dokumen'))
]);
But now i can't get it back when i try to edit(in editpage.blade), i want the checkbox is checked if it's value same as value in DB, how do do that guys ? please kindly help me solve
You used implode() to store, use explode() to retrieve.
$values = explode(",", $model->revisi_dokumen);
In your view you check if the checkbox value is in the array
<input type="checkbox" name="revisi_dokumen[]" value="1" {{ in_array('1', $values) ? 'checked' : '' }}>One

pass associative array in input field in form PHP

I want to know the best and easiest way to pass associative array in form inside input field. So far Ive done this and it all started to look messy and hard to handle.
$dish_result = $obj->getAll_dish();// this returns array all the rows in dish table
<form action='order_process.php' method='post'>
foreach ($dish_result as $dish){
echo '<input id="" name="dish_name[]" type="checkbox" value="'. $dish['dish_name'].'">';
echo '<input id="" name="dish_number[]" type="checkbox" value="'. $dish['dish_number'].'">';
}
</form>
Now on the order_process.php I have
foreach($_POST['dish_name'] as $dish){
echo $dish;
}
foreach($_POST['dish_number'] as $num){
echo $num;
}
What I wanted is an associative array, but how can I associate it the form dynamically. in other words I wanted to achieve this on the order_process.php.
$dishes = array(
//'dish_name' => dish_number
'chickencurry' => '70',
'onionbhajis' => '22'
// and so on.
);
Thank you very much in advance.
Create a grouping name first, then to get that kind of structure, make the dish name as key, then the value attribute holds the number. The basic idea is this:
name="dish[dishname]" value="dish_number"
It'll be like this:
echo '<input id="" name="dish['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'" />';
When you submit it with all the checkbox checked, it should be something like:
Array
(
[chickencurry] => 1
[onionbhajis] => 2
)
On the order_process.php page, just call it just like you normally do:
$dishes = $_POST['dish'];
foreach($dishes as $dish_name => $dish_number) {
}
Sample Output
You can add an index to array postdata. Try this:
foreach ($dish_result as $dish){
echo '<input id="" name="dishes['.$dish['dish_name'].']" type="checkbox" value="'. $dish['dish_number'].'">';
}
Your data will then be an associative array of the checked elements when posted back.

How to validate these elements in PHP?

I have checkboxes with the following names:
chk-cloud-a
chk-cloud-b
and so on...
chk-dco-a
chk-dco-b
and so on...
How do I validate after form submission such that:
Atleast one element from the checkboxes with name starting with chk-cloud or chk-dco must be ticked?
I hope someone can help me with this.
Cheers!
If they're checkboxes then all you really care about is whether or not they have a value. What that value is is not significant.
All you need to do is check that there are elements in the $_GET or $_POST (depending on form submission method) that contain fields of that name.
if (array_key_exists ('chk-cloud-a ', $_POST)) {
// Do what should happen of that checkbox is checked
}
If the problem is that you have multiple similar checkboxes then you might want to consider grouping them together in an array. This is done by using square bracket notation in the field name:
<input type="checkbox" value="1" name="chk-cloud[a]" />
<input type="checkbox" value="1" name="chk-cloud[b]" />
<input type="checkbox" value="1" name="chk-cloud[c]" />
<input type="checkbox" value="1" name="chk-cloud[d]" />
You can use a loop to process such a group
foreach ($_POST [chk-cloud] as $key => $value) { // We're really only interested in the key
handleCheckbox ($key) // handleCheckbox is some function you've wrote
}
Or
foreach (array_keys ($_POST [chk-cloud]) as $key) { // Logically the same as above
Just use preg_match or strpos to check if any key in POST matches Your requirements. Personally i would make subarray of these elements and just check if its empty.
try like this:
function checkBoxValidate(){ //method to test checkbox
$array = array('a','b','c','d', ....); // make array for each checkbox name
foreach ($array as $a){
if((isset($_REQUEST['chk-cloud-'.$a]) || isset($_REQUEST['hk-dco-'.$a])) && ($_REQUEST['chk-cloud-'.$a] == 'check_value' || $_REQUEST['hk-dco-'.$a] == 'check_value' ) ){
return true;
}
}
return false; //return no check box was checked
}

Check Box selected attribute set regardless of value

Try this at home:
Write a form to display a list of checkboxes in PHP:
$checkboxes = array('one' => 1, 'two' => 2, 'three' => 3);
$html = "<html><body><form name=\"myForm\" action=\"this\" method=\"post\"><ul>Check Test";
foreach ($checkboxes as $id => $value)
{
$checkVal = (isset($_POST['check_test'][$id])) ? 'true' : 'false';
$checkList = "<li><input type=\"checkbox\" name=\"check_test[]\" id=\"$id\"
value =\"$value\" checked=\"$checkVal\" />$name = $value</li>\n";
}
$checkList .= "<input type=\"submit\" value=\"Submit\">";
echo $html.$checkList."</ul></body></html>";
You will find that no matter what you put into the $checkVal assignment, when you hit submit, your checkboxes will all be checked. My workaround is to expand the $checkVal variable to set the entire "checked='' status to either something or nothing. I'm just surprised that Firefox (rather, Iceweasel) is only looking to see if the attribute is set at all. Why even have it if whatever it's set to is irrelevant?
Look at the source html. The selected attribute will display whatever you put into the checkval variable. The DOM specification states:
checkboxObject.checked=true|false
Here is my output:
<ul><li><input type="checkbox" name="check_test[]" id="one"
value ="1" checked="false" />one= 1</li>
<li><input type="checkbox" name="check_test[]" id="two"
value ="2" checked="false" />two= 2</li>
<li><input type="checkbox" name="check_test[]" id="three"
value ="3" checked="false" />three= 3</li>
And lo and behold! Every box is checked. Contrary to what I've explicitly expressed in the html.
The false is ignored. If the check attribute exists the box is checked.
foreach ($checkboxes as $id => $value)
{
$checkVal = (isset($_POST['check_test'][$id])) ? 'checked="checked"' : '';
$checkList = "<li><input type=\"checkbox\" name=\"check_test[]\" id=\"$id\"
value =\"$value\" ".$checkVal." />$name = $value</li>\n;
}

Categories