Welcome Guest, Not a member yet? Register   Sign In
[Solved] Null $_POST variables showing as undefined index?
#1

[eluser]WoolyG[/eluser]
Hi all,

I have a checkbox with a value of 1 in my form:

Code:
<?php
$email_please = array(
'name' => 'email_please',
'id' => 'email_please',
'value' => '1',
'name' => set_checkbox('email_please', '1'),
);
echo form_checkbox($email_please);
?>

and in the target file I am grabbings its value:

Code:
$email_please = $_POST['email_please'];

.. but if the checkbox is not checked I'm getting an Undefined index: email_please in my target file. Otherwise it sends "1" through.

Can someone point out what I'm doing wrong? Do I need to specify that the POST variable might be null, or not selected?

Thanks.

WoolyG
#2

[eluser]LuckyFella73[/eluser]
If a checkbox is not checked there is no POST value for that form element,
unlike with input fields type text or textareas.
#3

[eluser]WoolyG[/eluser]
How come the value is simply blank when the form is sent using standard php in that case?

Standard posting in non-CI php would return something like..
Code:
<?php $email_please = ""; ?>

How does codeigniter deal with checkboxes that are not checked? I want to assign a value of 1 or 0 depending on whether the box is checked or not. How would I go about this in CI?
#4

[eluser]LuckyFella73[/eluser]
Code:
How does codeigniter deal with checkboxes that are not checked?

It depends what you mean exactly. You can use the CI form validation
and repopulate the checkbox state in case the requiered fields are
not filled. In generall it's no CI issue that unchecked checkboxes
are not available in the post array.

In your case you can write something like:
Code:
if (!$_POST['email_please'])
{
    $value_email = '0';
}
else
{
    $value_email = '1';
}
#5

[eluser]WoolyG[/eluser]
Code:
if (!$_POST['email_please'])
{
    $value_email = '0';
}
else
{
    $value_email = '1';
}

.. the above code does not work. It errors for the line number containing:

Code:
if (!$_POST['email_please'])
.. with the same undefined index mesage as before.

The checkbox is not required, it's a simple "would you like email?" option for a registrant, so I'm not going to use a 'required' validation on it (though I use required checkboxes for other options in the same form).

What happens in CI when an optional checkbox is POSTed with no check in it? It must be a setting I'm not specifying. It can't be the case that it's not possible to set a 0 against a non-checked checkbox!!!!!

Anyone?

Thanks,
WoolyG
#6

[eluser]WoolyG[/eluser]
I've worked it out. I needed to use:

Code:
if(isset($_POST['email_please']) && ($_POST['email_please'] == "1"))
{
$email_updates = "1";
} else {
$email_updates = "0";
}

.. so there is a requirement to specify an isset() too. Thanks for your input guys! Marking this as solved.

Regards
WoolyG




Theme © iAndrew 2016 - Forum software by © MyBB