I have a front-end form submitting to my custom post type and checkboxes within.
<input type="checkbox" name="_my_checkbox[]" value="Yes"/> Yes
<input type="checkbox" name="_my_checkbox[]" value="No"/> No
<input type="checkbox" name="_my_checkbox[]" value="Maybe"/> Maybe
After that I saved it as post meta.
Then I need admin handling for this posts and values. As far as I've tried only accomplished to save and manipulate one value. I guess the problem is somewhere within the arrays.
Here it is a part of the function which displays the meta box.
$get_my_meta = get_post_meta($post->ID, 'my_meta', true);
$get_my_meta_data = array('Yes','No','Maybe');
foreach ($get_my_meta_data as $key => $value) { ?>
<input type="checkbox" name="_admin_my_checkbox[]" value="<?php echo $value;?>"<?php if($value == $get_my_meta){echo 'checked';} ?> /><?php echo $value;
}`
And then comes the saving function
if($_POST['_admin_my_checkbox']) {
$my_checkbox_updater = $_POST['_admin_my_checkbox'];
update_post_meta($post_id, 'my_meta', $my_checkbox_updater);
}
In this case when I check some of the checkboxes and use print_r values are saved as expected. I guess the problem is within foreach loop but have no idea what could be.
Quick edit. Found solution. in_array() function do the job perfectly.
foreach ($get_my_meta_data as $key => $value) { ?>
<input type="checkbox" name="_admin_my_checkbox[]" value="<?php echo $value;?>"<?php if(in_array($value,$get_my_meta)){echo 'checked';} ?> /><?php echo $value;
}
Related
I have 5 check boxes from which a user can select one or more choices. The selected choices are then updated in database. The user's choices are then displayed/reviewed on another page. However my issue is that I want to show the updated choices together with the non-selected choices when doing a foreach loop in PHP.
These are the 5 check boxes
<input type="checkbox" name="interest[]" value="fishing">Fishing
<input type="checkbox" name="interest[]" value="camping">Camping
<input type="checkbox" name="interest[]" value="hiking">Hiking
<input type="checkbox" name="interest[]" value="swimming">Swimming
<input type="checkbox" name="interest[]" value="running">Running
<br><br>
<input type="submit" name="submit" value="Submit">
Heres the code that updates
if (isset($_POST["submit"])) {
$interestArr = $_POST['interest'];
$interest = new Interest();
$newArr = implode(',', $interestArr);
$interest->updateInterests($id=19, $newArr);
}
Heres the code that displays
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
foreach ($newArr as $data) {
echo '<input type="checkbox" name="interest[]" value="'.$data .'" checked>'.$data;
}
The update choices are stored under the interests column in DB like so
fishing,camping,running
And the foreach loop displays them checked check box with the correct corresponding labels.
How can I display the other check boxes that were not selected just so that the user might want to make changes?
Thanks.
Here's a simple example to illustrate the main idea. This code is intended to run in the single script.
The main ideas are:
Use a global list of interests to drive the form.
Keep a separate global list of checked check boxes which you can compare to determine if the checkbox should be checked.
when the form is submitted, populate the list which keeps track of checked items
render the form and compare the list of available checkboxes with checked checkboxes. If item found in both lists, it means that we want to display the checkbox as checked.
index.php
<?php
// Keep this outside of the if statement so the form has access to it.
$availableInterests = [
'fishing',
'camping',
'hiking',
'swimming',
'running',
];
// Keep this outside of the if statement so the form has access to it.
$selectedInterests = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Cast the posted interests to an array in case the user submitted an empty list.
// An empty list would be NULL if we didn't cast it.
$selectedInterests = (array)$_POST['interest'];
// foreach $selectedInterests insert into DB...
// Let this code `fall through` to render the form again.
// $selectedInterests is now populated and can be used in to the form below to keep the selected checkboxes checked.
}
?>
<form method="post">
<!-- Using the `global` $availableInterests array to drive our form. -->
<? foreach ($availableInterests as $interest): ?>
<!-- Do we want to render the checkbox as checked? -->
<?php $checked = (in_array($interest, $selectedInterests)) ? ' checked' : ''; ?>
<input type="checkbox"
name="interest[]"
value="<?php echo $interest; ?>"
<?php echo $checked; ?>>
<?php echo ucfirst($interest); ?>
<?php endforeach; ?>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
Let's suppose you have an array of choice list like :
$choices = ["Fishing", "Camping" , "Hiking","Swimming" , "Running" ]
after the user select their choices
$interests = ["Fishing" , "Running" ];
In your case , the coresponding line is :
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$newArr = explode(',', $interests);
Let's suppose that $newArr is equal to $interests in may example.
foreach ($interests as $interest) {
echo 'you have choose '.$interest.PHP_EOL;
}
As result :
you have choose Fishing
you have choose Running
For not selected :
$notInterests = array_diff($choices,$interests);
foreach ($notInterests as $notInterest) {
echo 'you have not choose '.$notInterest.PHP_EOL;
}
As Result :
you have not choose Camping
you have not choose Hiking
you have not choose Swimming
To handle it in one loop :
foreach ($choices as $choice) {
if(in_array($choice,$interests )){
echo'you have choose '.$choice.PHP_EOL ;
}else{
echo 'you have not choose '.$choice.PHP_EOL;
}
}
Hope this help you.
To help others that might be in a similar situation I would like to post what is now a working solution at least for me based on Mohammed Yassine CHABLI's inspiration. Vantiya who was the first to comment really help me appreciate what was to follow. Thanks guys.
<?php
$interest = new Interest();
$interests = $interest->showInterests($userid=19)->interests;
$choices = $interest->showInterests($userid=19)->choices;
$selected = explode(',', $interests);
$choices = explode(',', $choices);
foreach ($choices as $choice) {
if(in_array($choice,$selected )){
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
checked>'.$choice;
}else{
echo '<input type="checkbox" name="interest[]" value="'.$choice .'"
unchecked>'.$choice;
}
}
I have multiple checkboxes within a foreach loop and I need to keep the selected checkboxes checked after the form submission. The code is as below. Please help.
<? $i=0;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
foreach($row=$val)
{
$id="chkbox".$i;
?>
<input type="checkbox" name="chkbx" onclick ="func()" id="<?echo $id;">? value="<?echo $val \n;?>" <? echo "$val";?>
Now where and how to include the checked property of the boxes..
You don't need foreach loop here
This can be done for checking multiple checkbox checked
<?php
$i=0;
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
$checked = "";
if($row['database_column_name']=$val){
$checked = "checked";
}
echo '
<input type="checkbox" name="chkbx" onclick ="func()" id="'.$id.'" value="'.$val.'" '.$checked.'>'.
$val
.'
';
}
?>
Works for me.
Ive got a 3 part form and i want to store the users selections in a session so if they need to go back and change a selection they can.
The form consists of radio buttons and checkboxes. I have it working for the radio buttons they are stored in a session so it always remembers.
I can't think how to go it working on the checkboxes as they are stored in an array.
This is my form:
So when they select jam and Flora, i get an array like this
Array ( [0] => Jam [1] => Flora )
This is my checkbox:
<input type="checkbox" name="<?php echo $course_menuname."extras[]"; ?>" <?php if($_SESSION[''.$course_menuname.''] == $extraitems) { echo "checked"; } ?> value="<?php echo $extraitems; ?>">
So i need a session to store each of the values they selected then if its one they selected put a check on the checkbox.
Hope this makes sense.
Thanks
i was also suffering from same problem, below solution worked fine for me, make appropriate changes before use,
<input type='checkbox' name='list[0]' id='product' value='Product'></input>
<input type='checkbox' name='list[1]' id='product' value='Product'></input>
Here I am setting my variable with the POST of the checkboxes.
$checkboxes = $_POST['list'];
$_SESSION['list'] = $checkboxes;
And use foreach so we know that in $_SESSION['list'] we have only checked ones!
foreach ($_SESSION['list'] as $key => $value)
{
echo '<input type="checkbox" name="list['$key']" value="'.$value.'" checked="checked >';
}
I am using the code below in my php file to get the values from a multiple checkbox.
if(!empty($_POST['check_list'])) {
foreach($_POST['check_list'] as $check) {
update_comment_meta($check, 'consider', 1);
}
}
The problem is that this code is apparently putting in the array $_POST['check_list'] only the checked values.
My need is to perfom the function update_comment_meta also on uncheked values, by putting '0' as the third parameter instead of '1'.
For more details, I give the code generating the HTML form:
<form action="" id="primaryPostForm" method="POST">
<?php
$defaults = array(
'post_id' => $current_post);
$com= get_comments( $defaults );
foreach ($com as $co) {
if(get_comment_meta($co->comment_ID, 'consider', true)==1) {
?><input type="checkbox" name="check_list[]" value="<?php echo $co->comment_ID; ?>" checked="checked">
<?php }
else {
?><input type="checkbox" name="check_list[]" value="<?php echo $co->comment_ID; ?>" >
<?php
}}
</form>
Your usual help is always appreciated.
sending unchecked value to post is somewhat not that easy.Better solution is that you name checkbox in a way using which you can easily iterate over them in post page.
Use hidden input along with checkbox.Checkbox prioritize over hidden input.
<form>
<input type='hidden' value='0' name='check_box_con'>
<input type='checkbox' value='1' name='check_box_con'>
</form>
Now after submit, as both have same name , check_box_con will show hidden field value if unchecked , else will override and show original.
For more see
Post the checkboxes that are unchecked
Here is the solution I used ( based on PeeHaa comment):
if(!empty($_POST['check_list'])) {
foreach ($com as $co) {
if (in_array($co->comment_ID,$_POST['check_list']))
update_comment_meta($co->comment_ID, 'consider', 1);
else
update_comment_meta($co->comment_ID, 'consider', 0);
}
}
In fact POST variable works like this with checkboxes, so the simple way is to use server side language to know what are values not sent via POST.
Thank you for your time.
Hello knowledgeable people. I am having trouble retrieving checkbox data from form. I have a site in which user can add checkboxes themselves, so I am writing them out like this:
<table style="padding:10px;">
<?php
$query_boolean = $DB->prepare("SELECT * FROM moduls WHERE type='boolean'") or die(mysql_error());
$query_boolean->execute();
while (($row = $query_boolean->fetch()) != false)
{
?>
<tr>
<td>
<?php echo $row->name ?>:
</td>
<td>
<?php
$s = "";
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="yes">%s', $row->id, Yes);
$s .= sprintf('<input type="checkbox" class="textbox" name="boolean_%s" value="no">%s', $row->id, No);
echo $s;
?>
</td>
</tr>
<?php
}
?>
</table>
Now I have an advanced search in which I have to chech through every checkbox to see what has been selected (ether none, Yes, No, or both). How can I get the info from every checkbox in variables? Thank you so much!
To get POST data from checkboxes they must have attribute
checked="checked"
EDIT:
If you have 2 checkbox as this..
<input type="checkbox" checked="checked" class="textbox" name="boolean_yes" value="yes">
<input type="checkbox" class="textbox" name="boolean_no" value="no">
When you submit your form the checkbox with attribute checked will be sent as POST and the one without checked attribute will not be sent..
if(isset($_POST['search'])) {
$all_checked = array();
foreach($_POST as $key=>$value){
if(strpos($key, "boolean_") > -1){
$all_checked[$key] = $value;
}
}
var_dump($all_checked);
}
This way you will get inside $all_checked array all marked boxes.. All others checboxes are not marked!
if you want to get checkbox value then use checkbox name as array
<input type="checkbox" name="email1[]" value="">
an get it on another page by
<?php
$var2 = $_POST['email1'];
$v=implode(",",$var2);
echo $v;
?>
try it