php function that checks if checkbox is selected. Field validation issue
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;
}
No comments:
Post a Comment