I have a form and inside I have a table and each row I have checkbox
like this: <input type="checkbox" name="register[]" value="123-3-158-855">
When I click on the submit button to send to controller, return only NULL values from checkbox
public function update_rows()
{
$data= $this->input->post('register');
var_dump($data);
}
What's the problem? I can't see.
Edit: I found the problem, I'm using datatable in my table and when I removed works fine, but why???
It's important to understand that if a checkbox is unchecked when its form is submitted, there is no value submitted to the server to represent its unchecked state (e.g. value=unchecked); the value is not submitted to the server at all. In other words, when not checked then $this->input->post('register'); will return NULL.
In the case of a field name array i.e. name="register[]" only the values for the checked boxes will be in the array.
Related
I'm working with forms where the checkboxes are present, but the target model's fields must be in boolean type, since they are defined in my migrations as boolean. For example:
$table->boolean('is_active')->default(true);
The Model's values are filled in this way:
foreach (static::getFillableFields() as $field) {
$entry->$field = $request->input($field);
}
So I added the cast to make this field boolean:
class Entry extends Model
{
protected $casts = [
'is_active' => 'boolean',
];
But now what I see: when the form's checkbox is checked and I have '1' string in the request, it works well - '1' gives 'true' when I access $entry->is_active then. But when checkbox isn't checked, it gives the 'null' value, and - I don't know why - when the model's field is set to null, then it returns null (not 'false', as I expected).
Why is it so? This makes casts useless in my case. Can I change this behavior?
I'm not too inspired with idea of adding this (accessors/mutators) for every boolean field (but in fact this results in what I need):
public function setIsActiveAttribute($value)
{
$this->attributes['is_active'] = (bool)$value;
}
public function getIsActiveAttribute(bool $value): bool
{
return $value;
}
As #Devon mentioned, checkboxes that are not checked are not included in the request data sent to the controller. The HTML spec deems unchecked checkboxes as unsuccessful, and therefore does not submit them.
One trick that is used to get around this "limitation", however, is to add a hidden input to your HTML that has the same name as your checkbox, but contains the false value. This hidden input must come before your checkbox input.
This will allow you to continue to use your mass-assignment functionality.
So, your form should look something like:
<input type="hidden" name="is_active" value="0" />
<input type="checkbox" name="is_active" value="1" />
Now, when the form is submitted with an unchecked checkbox, the hidden input will ensure the input value exists in the request data with the false value (0).
When the form is submitted with a checked checkbox, both inputs will submit successfully with the same name, but the server side will only take the last value it sees. This is why the checkbox must come after the hidden input field, so that the last value the server sees is the successful value defined on the checkbox (1).
As a side note, this is also how the Ruby on Rails form helper handles checkboxes. From their documentation.
The HTML specification says unchecked check boxes are not successful, and thus web browsers do not send them. Unfortunately this introduces a gotcha: if an Invoice model has a paid flag, and in the form that edits a paid invoice the user unchecks its check box, no paid parameter is sent. So, any mass-assignment idiom like
#invoice.update(params[:invoice])
wouldn’t update the flag.
To prevent this the helper generates an auxiliary hidden field before the very check box. The hidden field has the same name and its attributes mimic an unchecked check box.
This way, the client either sends only the hidden field (representing the check box is unchecked), or both fields. Since the HTML specification says key/value pairs have to be sent in the same order they appear in the form, and parameters extraction gets the last occurrence of any repeated key in the query string, that works for ordinary forms.
This is a controller issue, not a model issue. HTML checkboxes will not have a value if they are unchecked, this is how they work.
Therefore, when retrieving the value from your Request object in the controller, you should set the default value as false.
Example in controller method:
$model->is_active = $request->input('is_active', false);
If you leave the second argument of input() empty, it will default to null.
Suddenly: casts don't work for Model::save() method.
laravel eloquent model casts on save?
So all that's left for me is to use accessors/mutators..
The form used to add a new item into the database and edit existing items is the same form. A "Mode" is passed into the form to tell it if were adding something new or to load the existing item for editing. So....
<input type="checkbox" name="fflreq" id="fflreq" value="<?=$row['FFLr']?>" <?php if ($row['FFLr']=="Yes") {echo 'checked';} ?>>
When a new item is being added, $row['FFLr'] doesn't exist so of course the value is BLANK or NULL or i guess 0 if i don't initially check the checkbox- The form processor coverts this into a "No" and inserts it into the database.
Now here is my problem - When I come back to a item and the form is in edit mode, the VALUE in this checkbox is now "No" - when I am clicking the checkbox to change its status, I see the checkbox become 'checked' but the value is not changing. in other words the click/check status is not setting the value of $_POST['fflreq'] to YES or 1.
I thought, that checking or unchecking a form checkbox replaces whatever is currently in the value='' attribute with a 1 or 0 to represent yes/no on/off or whatever. Why would the value pulled in from the database not change on form submission?
You need to do it in this way:
<input type="checkbox" name="fflreq" id="fflreq" value="Yes" <?php if ($row['FFLr']=="Yes") {echo 'checked';} ?>>
and when submit the form if the above checkbox is checked then you recieved the $_POST["fflreq"] in the form submit page and if it is not checked you recieve nothing in $_POST
so in the submit page you can do this:
$fflreq = "No"
if(isset($_POST["fflreq"]) && $_POST["fflreq"] == "Yes")
{
$fflreq = $_POST["fflreq"];
}
//then you can simply do anything with the $fflreq such as inserting it into database etc.
I hope this can be of some help.
That's not how it works. If you have "checked" the check box then it (along with it's value) will be sent with the post/get (i.e. submission) of the form. If you haven't checked it, then it won't be set...
If the checkbox is active, the browser sends the key/value pair defined in the input tag. However, if the checkbox is not active, nothing at all is sent for this checkbox.
There are two options to deal with this:
The clean option is to be aware of this on the server side, and assume that the checkbox was not active whenever no value comes through.
A more dirty variant is having a <input type="hidden"> tag just before the checkbox, using the same name, but the value you need to see when the checkbox is inactive. This way, when the checkbox is active, you'll still get the desired value from the checkbox, because it will overwrite the hidden value. However, if the checkbox is inactive, you'll get the value from the hidden field.
Not really, the check/unchecked status is read out by looking if the HTML name attribute value is present in the $_POST param.
You can check this with:
<?
if (!empty($_POST['fflreq'])){ /*checked*/ }
else{ /*unchecked*/ }
?>
The value of the HTML attribute value always stays whatever it is in your HTML. So no user interaction (except JS) can change that.
Working with PHP empty() function lets you bypass all the "Yes" "1" string int casting issues.
Further I would use ternary notation for these kind of things:
<input type="checkbox" name="fflreq" id="fflreq"
value="<?=$row['FFLr']?>" <?=(!empty($row['FFLr'])?'checked':'')?>>
I have a symfony form with many checkboxes :
$this->form = new SocialSettingsForm($user);
if ($request->isMethod(sfRequest::POST)) {
$this->form->bind($request->getParameter('social'));
if ($this->form->isValid()) {
$this->form->save();
$this->success = true;
}
}
The problem is the following : after saving the form, the checkboxes act weirdly
If the user checked one, it appears checked after the save (normal behaviour)
But if the user unchecked one, it will still appear checked after the save.
I did a var_dump on the form values, unchecked checkboxes have a NULL value, so i don't
understand why they are still checked.
Thanks for your help.
If you use boolean / integer field for saving the checkbox value, use sfValidatorBoolean for your checkboxes. It also converts the input value to a valid boolean. So null will be converted to 0 and will be saved in the database.
Update with workaround
In older versions where this do not work, you can add hidden input with the same name as the checkbox and value of 0, before the checkbox. If the checkbox is not checked, the hidden input value will be sent, otherwise the checkbox value will be sent.
I have a few checkboxes in my form and I need to change their value when the checkbox is checked.
For example this is one of the checkboxes:
<input type="checkbox" name="drink" value=""/>
I know .val() can change it but I wasn't able to do this with if statement.
I appreciate your answer in advance.
What you are seeking is actually very meaningless. See, when a form is submitted, only the checked checkboxes actually send values, so it makes no sense to change the value especially for the unchecked checkbox.
Better Solution
You should instead give it the "checked" value, and keep it that way, that will cause it to submit correctly even without changing the values.
You can add a click event listener on the checkbox:
$('input[name="drink"]').click(function() { // when click on it
if ($(this).attr('checked')) { // if the checkbox is checked
$(this).val("value #1"); // change the value
} else { // otherwise if is unchecked
$(this).val("value #2"); // change the value
}
});
// attach an onchange handler to all checkboxes on the page
$("input[type='checkbox']").change(function() {
// or if($(this).prop("checked")) {
if(this.checked) {
$(this).val("value for checked");
} else {
$(this).val("value for unchecked");
}
});
The onchange event is the one you should be interested when it comes to checkboxes, as it fires whenever you change the checked state of it.
The checked property determines whether or not the checkbox has been checked.
The .val() method allows you to conveniently read/write element values.
Given that when using an html radio box, to send values to a php script, only the selected values is sent to the php script, still holds true.
Do I still need to check that the user has selected something, when I am only interested in the selected value being sent to the php script, if the user does not select anything we do nothing or I guess I could prompt the user to select something.
If so, whats the best way to handle this with regards to radio boxes?
<!--Using the radio box, a single selected value is sent to the php script for processing-->
<td width="100px" height="30px">
<input type = "radio"
name = "selection"
value = "Lays" />Lays Chips 0.99c<br />
<input type = "radio"
name = "selection"
value = "Ruffles" />Ruffles $1.85<br />
The user will be able to click the "submit" button even without selecting an option from your radiobox.
If it's ok to send the form without a selection and you just want to do something different (or ignore it) when nothing is selected, you can do this:
<?php
if (isset(($_POST['selection'])) {
//Use it.. and make sure to validate user input.
} else {
//nothing was selected. Do something or just ignore?
}
?>
OTOH, if you want to prevent submiting without a selection, you will need to use some JavaScript to do it.
Even if the radiobox is not set, you can still post the form back to the server. Unless, of course, you have Javascript that prevents one from clicking on the submit form if the radiobox is not set.
So, you still need to check whether the radiobox is set or not, before working on it.