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..
Related
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.
I have ActiveForm checkbox:
<?= $form->field($model, 'is_necessary')->checkbox(['uncheck'=> 0]) ?>;
I want to make it checked by default and when I check, it's value become 1 and when uncheck - 0. Can I achieve this without any javascript?
I tried :
<?= $form->field($model, 'is_necessary')->checkbox(['uncheck'=> 0, 'value'=>false]) ?>;
option 'value'=>false made my checkbox checked by default but then in controller I receive NULL nor either 1 or 0.
just add in your controller or view (which is not recommended) below code
$model->is_necessary = true;
above code works fine. but you should add this code before your
$model->load(Yii::$app->request->post)
method or assigining post data to your model. Otherwise your checkbox will be checked any time;
The best approach is to override init() inside your model
public function init() {
parent::init ();
$this->is_necessary = 1;
}
and you don't need to pass the 'uncheck'=> 0, as per the DOCS
uncheck : string, the value associated with the unchecked state of the
radio button. If not set, it will take the default value 0. This
method will render a hidden input so that if the radio button is not
checked and is submitted, the value of this attribute will still be
submitted to the server via the hidden input. If you do not want any
hidden input, you should explicitly set this option as null.
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':'')?>>
All,
I have the following bit of PHP to check a checkbox:
<input type="checkbox" name="check_out_gear[]" id="'.$resultsetgear['gear_checkout_id'].'" value="'.$resultsetgear['gear_checkout_id'].'" class="gear_checkout_checkbox" checked disabled>
That code works fine and the checkbox is checked and it is disabled. I'm checking to see if it at least one checkbox is checked by using the following jQuery:
var fields = jQuery(".gear_checkout_checkbox").serializeArray();
if (fields.length == 0)
{
jQuery.wl_Alert('Please select a piece of equipment that you\'re checking out!','warning','#no_answers','#workform', {sticky:false});
one_selected = false;
}
When that checkbox is checked and disabled the length is always 0. However as soon as I remove the disabled from the code it has a length of at least 1. Any idea how I can get this code to work with a disabled checkbox?
serializeArray mimics a form submitting. When a form is submitted, disabled elements do not get sent.
Use is(":checked") instead.
jQuery(".gear_checkout_checkbox").is(":checked")
From the docs:
The .serializeArray() method uses the standard W3C rules for
successful controls to determine which elements it should include; in
particular the element cannot be disabled and must contain a name
attribute.
This is documented behavior for disabled inputs. From the jQuery docs on .serializeArray():
The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute.
Just check for the length of the checked boxes using the :checked selector [jQuery docs], like so:
if (jQuery(".gear_checkout_checkbox:checked").length === 0)
A disabled checkbox will not be sent, regardless of whether it is checked or not. Therefore it won't be picked up by serializeArray. You should check whether the checkbox itself is checked, not if it would be submitted.
A disabled input will not show up because it is disabled. The fact that it is checked is of no consequence.
If you're using jQuery to enable and disable the checkbox, you could use jQuery to also set a value on a hidden input when disabling the checkbox (and to change it again when the checkbox is enabled again). You can then process the hidden input along with the checkboxes and do the correct thing.
Another possibility is to not disable the checkbox at all, but then use CSS changes to indicate it is locked and catch the onchange event to prevent it from being modified.
You can use length property of jQuery object not the length of the array that is returned by serializeArray() method, try the following:
if ($(".gear_checkout_checkbox:checked").length === 0) {
jQuery.wl_Alert('Please select a piece of equipment that you\'re checking out!','warning','#no_answers','#workform', {sticky:false});
one_selected = false;
}
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.