check box checked by default in yii2 ActiveForm - php

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.

Related

yii2 gridview filterSelector doesn't consider unchecked input

I use GridView in Yii2 framework.
'filterSelector' => 'input[name="AccountSearch[field]"]',
<?= Html::checkbox('AccountSearch[field]', $searchModel->field == true, [
'label' => 'Field', 'value' => 1
]) ?>
When I click it first time - it works well. But when I click more times - checkbox stays always checked. And in http request I see that pjax always sends 'field' = 1. Gridview or pjax bug ?
The hidden input is automatically generated by default.
link
uncheck: string, the value associated with the uncheck 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

How to make casts work in this way?

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..

laravel read a checkbox value in a controller

This is my html blade code
{{Form::checkbox('remember_me', '', array('id'=>'remember_id'))}}
<label for="remember_id">Remember me</label>
This is my controller code:
echo Input::get('remember_me');exit;
The result is always empty, why please?
The checkbox is always checked when I run the page, why please?
Thanks
Please have a look on the [parameter list of the Form::checkbox() method][1].
The second parameter is your checkbox value. You manually set it to an empty string. Set it to null in order to keep the browsers default values (laravel default is 1). The third parameter is a boolean. Set it to true to check the box and false to uncheck it.
The fourth parameter is your options array where you can specify your id. So the correct method call should be:
{{Form::checkbox('remember_me', null, false, array('id'=>'remember_id'))}}
Update:
Checkboxes that are not checked, will not be included in your POST data. So the only reliable way to verify that a checkbox has been checked is to check if it is set. That can be done using isset() with regular PHP functions, or if laravel is being used, by using Input::has() which returns a boolean dependent on whether your input data contains a given key.
You did not add a value to the checkbox
{{Form::checkbox('remember_me', 'value goes here', true, array('id'=>'remember_id'))}}
The second param is the value
Normally I write the checkbox without blade and I can do with it whatever I want, like normal HTML. I don't see why you can do it the normal HTML way, because it always ends up doing the same thing you expert.
{!! Form::label('Test-2') !!} {!! Form::checkbox('ch[]', 'value-2', false); !!}

Override checkbox value set by PHP

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':'')?>>

Symfony form : old values are displayed after saving

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.

Categories