Please read my issue carefully, it's a bit tricky.
The function below is used to display whether a checkbox has been checked in a form on both of my 'add' and 'edit' record pages. No problem here.
The problem:
Let's say I have 2 fields 'name' and 'enabled'. Only fields that is validated is 'name'.
When a user edits an existing record and enters an invalid 'name', the form gets validated. If the user un-checked the 'enabled' checkbox (prior value was $field_record_value="1", setting from the database), the checkbox value still set as "1" as it's still coming from the database.
Question:
How do I get the value to set as "0" when the database record ($field_record_value) is set to 1 ?
I know the issue lies in this code:
$is_checked = isset($field_record_value) ? $field_record_value : '0';
I can't seem to figure it out, maybe because I've spent about 2 hours on this and my brain is fried..but I digress :)
//------------------------------------------------
// Function to check if checkbox is selected
//------------------------------------------------
function form_checkbox_selected($field_name, $page = 'add', $field_record_value = '0')
{
if(!empty($_POST[$field_name]) && intval($_POST[$field_name]))
{
$is_checked = '1';
}
else
{
if($page ==' edit')
{
$is_checked = isset($field_record_value) ? $field_record_value : '0';
}
else
{
$is_checked = '0';
}
}
return $is_checked;
}
The problem is that you are expecting an unchecked value for a checkbox, the browser will never send a value for an unchecked checkbox, so the only way you can know a checkbox is in it's unchecked state is by assumption, which you can only assume after the form has been submitted. I would rewrite your function like so:
function form_checkbox_selected /// line wrapped for SO read-ability
($field_name, $page = 'add', $form_submitted = false, $field_record_value = '0'){
if ( form_submitted ) {
$is_checked = !empty($_POST[$field_name]) ? 1 : 0;
}
else if ( $page == 'edit' ) {
/// isset is not required because it will always
/// be defined by $field_record_value = '0' in default params.
$is_checked = $field_record_value ? 1 : 0;
}
else {
$is_checked = 0;
}
return $is_checked;
}
In order to tell if the form has been submitted or not, it is usually best to have a hidden field that you know will always be sent, or you can define a name for your submit button.
<form>
<input name="sent" type="hidden" value="1" />
</form>
<form>
<input name="sent" type="submit" value="Submit Form" />
</form>
Then on the php side you can call your function:
form_checkbox_selected(
'my_field', 'edit', !empty($_POST['sent']), $db['my_field']
);
This now means your php can make a better assumption of what the field's state is when no data has actually been passed in.
Related
I have a form field in my website which i use for a table in my database. i'm using checkboxes for a true/false value. In my case my checkboxes send out an empty string if left unchecked.
I made an if else statement to make sure the empty string is made boolean. however, my if else statements only works for the first one ($ringe). the last two ($halskaeder and $armbaand) does not seem to work, as my database does not register any inputs.
I'm guessing my if else statements has flaws or syntax errors, i'm just too hopeless at PHP to figure out what's wrong.
if ($_REQUEST['ringe'] == ""){
$ringe = '0';
}
else {
$ringe = '1';
}
if ($_REQUEST['halskaeder'] == ""){
$halskaeder = '0';
}
else {
$halskaeder = '1';
}
if ($_REQUEST['armbaand'] == ""){
$armbaand = '0';
}
else {
$armbaand = '1';
}
Any help is highly appreciated!
UPDATE!!!
So I realized my issue is that an unchecked checkbox in html doesn't send and signal. So i have to change that no matter what
AFAIK the check box is not sent if it's not checked. You can do something like:
$default = array(
'ringe' => 0,
'halskaeder' => 0,
'armbaand' => 0,
);
$myFormParams = array_replace($default, $_REQUEST);
var_dump($myFormParams);
few Suggestions... I may add more if you post your form..
1) Trim whitespace from user input (unless you need it)
$input = trim($_REQUEST['user_input']);
2) In this case, you should use empty(), because this function checks to see if the variable exists, and if it's empty, and if it's falsy. You can kill three birds with one stone.
3) Use ternary. It's shorthand for what you're doing.
$input = trim($_REQUEST['user_input']);
$input = empty($input) ? "0" : "1";
I found an answer. My problem wasnt the php code, but the checkboxed not sending any input when unchecked. The workaround is simply putting a hidden input field to send a false signal no matter what. You give it the same name attribute as your real checkbox, which will override when checked.
looks like this:
<input type="hidden" name="ringe" value="0" /><input type="checkbox" name="ringe" value="1" /><p>Ringe</p>
thanks for the help though!
I works on the an data-edit form in codeigintier. And the problem is about re-populate checkbox
It works if it is an add form (that means I need not concern about the value in database):
<?= set_checkbox('is_default', '1'); ?> for checkbox
The problem is, in the edit form:
I can't repopulate the checkbox
<?php if ($customer_group[0]['is_default'] == "1") echo "checked"; set_checkbox('is_default', '1'); ?>
The checkbox will check even I have not check it in the edit => fail to validate in the form, thanks for helping
I have already set the validation rule in controller, the code in the add form is working , but how to handle the case for edit form?
In order to re-populate checkbox following code might be helpful:
set_checkbox('fieldName', 'fieldValue');
Where 'value' is the second parameter of the form_checkbox call. Like this:
form_checkbox('fieldName[]', 'value', set_checkbox('fieldName', 'value'));
Now if you are on edit form then below code might help you
$getVal=$valFromDb; //$valFromDb is actually value of the filed from db as you are on edit page
if($getVal!=0){
{
echo form_checkbox('fieldName[]', 'value', true);
}
else
{
echo form_checkbox('fieldName[]', 'value', false);
}
set_checkbox takes a third argument to set the default state, so basically you have to do something like this
echo set_checkbox('is_default', 1, $customer_group[0]['is_default'] == "1");
Can give one suggestion??
1. Hide all the checked value of checkbox in input box when you are directed towards edit page.
If checked box is checked in edit page, edit the value of hidden input field of textbox value.
Submit it, when validation failed, checked or repopulate the checkbox value according to hidden field value. send checkbox value of checked box field through array from controller to edit page view like this. e.g $data['repopulate_checks'] = $this->input->post('array name of checkboxs');
In view :
getit like this
$catch_checkbox = $repopulate_checks;
You can directly get through $repopulate_checks also.
Hope this help you.
You can use form_checkbox() function: Guide
$isChecked = False; // or True for default value
If have stored data then:
$isChecked = $customer_group[0]['is_default'];
echo form_checkbox('input_name', 'value', $isChecked);
or the hard way:
set_checkbox():
The first parameter must contain the name of the checkbox, the second
parameter must contain its value, and the third (optional) parameter
lets you set an item as the default (use boolean TRUE/FALSE)
<input type="checkbox" name="is_default" value="1" <?php echo ($customer_group[0]['is_default']) ? set_checkbox('is_default', '1') : '' ; ?>/>
set_checkbox takes a third argument to set the default state, so basically you have to do something like this
$checked = FALSE; if($customer_group[0]['is_default']){ $checked = TRUE; }
echo set_checkbox('is_default', 1, $checked);
Hello I'm having some problem.
I want it to be checked by default, and if you unselect it and press submit I want it to be unchecked
<input type="checkbox" name="show_signature" value="1"<?php echo isset($_POST['show_signature'])) ? ' checked=""' : '' ?>>
This works good unchecking > submitting and checkbox is unchecked and same if you check it and send the form, it stays checked.
But, I want it to be checked by default. Should'nt this work?
if (isset($_POST['show_signature'])) {
echo ' checked=""';
} else {
echo '';
}
Tried this to
if (isset($_POST['show_signature']) || !isset($_POST['show_signature'])) {
echo ' checked=""';
} else {
echo '';
}
Okay; from the question, I got this process
When the page loads the first time, you want the checkbox to be checked.
When the page is submitted, if the checkbox is unchecked, let it remain unchecked; otherwise, let it be checked.
Try
/*making the assumption that the submission process starts when a submit button
with name **submit** is present, use this
*/
if (isset($_POST["submit"])){
value = '<input type="checkbox" name="show_signature"';
value .= (isset($_POST["show_signature"]))? 'checked="checked"': "";
value .= ' />';
print value;
}
else{ //when the page is initially loaded
print '<input type="checkbox" name="show_signature" checked="checked" />';
}
The reason the post depends on the submit button (or any other field)t is because if the user unchecks the box, the $_POST["show_signature"] variable will not be found, and the form will not be processed at all.
That should resolve the issue.
Hope the explanation is clear and this helps.
I have a page with search form on it and table with search results below. In search form i have checkbox "Search in this category". What i'm doing to check it by default :
if(!isset($_SESSION['inthiscat'])){
$_SESSION['inthiscat'] = 'on' ;
$checked = 'checked';
}
$_GET['inthiscat'] = $_SESSION['inthiscat'];
checkbox code : INPUT type="checkbox" name="inthiscat"<?=$checked?>.
Link to next page of results index.php?inthiscat=$_GET['inthiscat'].
So the problem is when i uncheck "Search in this category" its still checked when i going to next page of results. How to fix it and what i'm doing wrong? Session startet of course.
Firstly, do you really need SESSION variables for this? If you want box to be checked when GET parameter is not specified, you do not need SESSIONs at all.
Assuming you want to preserve the behaviour in case someone removes the GET parameter:
<?php
session_start();
//......
//......
$checked='checked';
if(isset($_REQUEST['inthiscat'])) {
// Form input and url GET parameters take precedence
if($_REQUEST['inthiscat'] != 'checked') { $checked = ''; };
} else if(isset($_SESSION['inthiscat'])) {
// Next, use session variable if it exists
if($_SESSION['inthiscat'] != 'checked') { $checked = ''; };
};
$_SESSION['inthiscat']=$checked;
?>
Note:
1) Assigning values to GET array is not a good practice.
2) I assume you are using correct syntax for your FORM submit.
3) IMO, you could remove the SESSION variable as you are explicitly passing as GET parameter in the subsequent urls. Or dont use the GET parameter in urls.
Problem is: when you uncheck the checkbox and go to the next page, $_SESSION['inthiscat'] will still be unset - where did you change it?
Here is the code:
if (isset($_GET['inthiscat'])) {
$_SESSION['inthiscat'] = $_GET['inthiscat'];
}
if (!isset($_SESSION['inthiscat'])) {
$checked = 'checked';
} else {
if ($_SESSION['inthiscat'] == 'on') {
$checked = 'checked';
} else {
$cheked = '';
}
}
Assuming this HTML: <INPUT type="checkbox" name="inthiscat" checked="<?=$checked?>" value="on" />
So what it does is:
Looks for the GET data and, if there is, assigns it (can be 'on' or '') to the SESSION;
If there is no SESSION (that means, no GET as well) it's the first page of that kind the user visits, so checked;
If there is a SESSION for inthiscat, it means it's not the first page and GET data has been assigned to the SESSION. So, if it's on, it displays the mark; else, it does not.
I have a php function script that is supposed to uncheck a checkbox or checkboxes if a user unchecks it when the preview button is clicked but I can only get the last
checkbox that was unchecked to stay unchecked but not the other checkeboxes how can I fix this so that all the checkboxes that where unchecked stay unchecked?
Here is part of my PHP function that is giving me the problem.
if(isset($_POST['preview'])){
foreach($query_cat_id as $qci) {
if(!in_array($qci, $cat_id)){
$unchecked = $purifier->purify(strip_tags($qci));
}
}
}
for ($x = 0; $x < count($query_cat_id); $x++){
if(($query_cat_id[$x] == $cat['id']) && ($cat['id'] != $delete_id) && ($cat['id'] != $unchecked)){
echo 'checked="checked"';
}
}
Why not just just check if the variable is set, if the checkbox is checked when the form is submitted, it will be available in $_POST['checkboxName'], otherwise, isset($_POST['checkboxName']) will return false.
Basic script to test it
<?php
if (isset($_POST['heh']))
echo $_POST['heh'];
else
echo "Not checked";
?>
<form action='yourPage.php' method='post'>
<input type='checkbox' name='heh' />
<input type='submit' />
</form>
View it in action
http://robertsquared.com/so.php
i solve this problem on client side
i have a input of type hidden with the same name as the checkbox with the value of 0 and the checkbox right after the hidden field with the value of 1
if the checkbox is not checked i get the value of 0 from the hidden field and if someone checks i got the 1 from the checkbox.
so i only need to check if $value==1 then checked=checked