Best way to handle checkbox in Laravel4? - checkbox

I'm starting to work with Laravel4, I was struggling with some basic stuff like this one below. There's any other way to handle the value for an unmarked checkbox than adding a hidden checkbox for the default value like below?
<td class="text-center">
{{Form::hidden('status', 0)}}
{{Form::checkbox('status')}}
</td>
This is working fine for me right now, but I would like to know if there's any better way like handling the value in the Controller#update.
EDIT: The values of the checkbox on the form are being handle by Input::all() at the Update action.
Thanks for the feedback.

This is default behavior of HTML actually, not related to how Laravel handle inputs. From HTML spec:
When a form is submitted, only "on" checkbox controls can become successful.
...
Every successful control has its control name paired with its current value as part of the submitted form data set.
So, a more generic approach would be not to change your HTML form, but change the behavior when you are retrieving the input, e.g.:
$status = Input::get('status', false);

In the FormBuilder class, the checkbox method has these parameters.
checkbox(string $name, mixed $value = 1, bool $checked = null, array $options = array())
So you want:
Form::checkbox('status', 0, false, ['class' => 'form-control'])
Happy coding!

Related

AngularJS: how put correct model to repeated radio buttons

I think I have some sort of special code here as all I could google was "too simple" for my problem and it also didn't helped to come to a solution by myself, sadly.
I got a radio button group of 2 radios. I am iterating over "type" data from the backend to create the radio buttons.
My problem is the data binding: When I want to edit an object its "type" is set correctly, but not registered by the view so it doesn't select the desired option.
Follwing my situation:
Backend providing me this as "typeList":
[
{"text":"cool option","enumm":"COOL"},
{"text":"option maximus","enumm":"MAX"}
]
HTML Code:
<span ng-repeat="type in typeList track by type.enumm">
<input
type="radio"
name="type" required
ng-model="myCtrl.object.type"
ng-value="type">
{{type.text}}
</span>
Some Explanation
I don't want to use "naked" texts, I want to use some sort of identifier - in this case it is an enum. The chosen value shall be the entire "type", not only "type.text" as the backend expects type, and not a simple String.
So all I do with this is always a package thingy, the type.text is for like formatted/internationlized text etc.
A Pre-Selection works by setting this in the controller: this.object.type = typeList[0];
The first radio button is already selected, wonderful.
But why isn't it selected when editing the object. I made a "log" within the HTML with {{myCtrl.object.type}} and the result is {"text":"cool option","enumm":"COOL"}. The very same like when pre selecting. I already work with the same "technique" using select inputs, and it works fine. I also found some google results saying "use $parent because of parent/child scope". But 1) I didn't get that straight and 2) think it is not the problem here, as I use a controllers scope and not the $scope, or is this thinking wrong?
It might be explained badly, sorry if so, but I hope someone 1) get's what I want and 2) knows a solution for it.
Thank you!
If you're trying to bind to elements from an array, I believe you need to assign the actual elements from the array to your model property.
So this creates a new obj and sets it to $scope.selectedType (not what you want):
$scope.selectedType = {"text":"cool option","enumm":"COOL"};
whereas this assigns the first element of the array (which is what you want)
$scope.selectedType = $scope.typeList[0];
So to change the model, you can lookup the entry from the array and assign it to your model with something like this
$scope.selectedType = $scope.typeList.filter(...)
Here's a quick example of this approach http://plnkr.co/edit/wvq8yH7WIj7rH2SBI8qF

AngularJS inconsistent databinding

I'm learning AngularJS and I have a question regarding the databinding for select elements. The databinding for textboxes works without any kind of event handling code. Once the ng-model attribute is set textbox updates when the model property changes and vice versa. There is no need for ng-change attribute.
However, for select elements we need to write functions that will be called via ng-change atribute.
Why does angularjs handle databinding without an ng-change attribute for textboxes but requires functions that will be called via ng-change attribute for select elements?
UPDATE:
Added the fiddle in the comments section. The example is from AngularJS in Action book. Click on one of the stories, change the textbox value and the model is updated. Change the selection in dropdown model is not updated.
UPDATE:
Added a new fiddle in the comments.
Thanks.
I've created a fiddle that works here - The issue is really just the dummy data here. In the original fiddle, the object created in the statuses array for {name:'Back Log'} and {name:'To Do'} are not the same (not ===) as the {name:'Back Log'} and {name:'To Do'} objects created in the dummy story objects.
To make the example work, I pass the indexed statuses into the getStories function. However I think this is really just a case of demo-induced confusion. (I've been looking at the MEAP for Angular in Action as well, and I think it could be simplified a bit like this one, that uses simple string statuses that will pass the === test
var getStories = function(statusesIndex) {
var tempArray = [
{title:'Story 00',
description:'Description pending.',
status: statusesIndex['To Do']
},
{title:'Story 01',
description:'Description pending.',
status: statusesIndex['Back Log']
}
];
return tempArray;
}
I think your confusion might be a result of the select documentation still being incorrect. (See my Disqus comment.) ng-model can and should be used with select. ng-change is optional and it just gives you a hook should you want to do something each time the selected option changes.
Normally you should use ng-options with select.
If i understood your question correctly then I think your guessing is wrong because for select boxes, you do not have to invoke ng-change event in order to fetch the selected option.
<select ng-model='select'>
<option>....</option>
<option value='one'>One</option>
<option value='Two'>Two</option>
</select>
// Your selected option will print below... without invoking ng-change
<div>You selected: {{select}}</div>
Demo: http://jsfiddle.net/jenxu/1/

Cakephp - keep selected value for dropdownlist after submit

How can I keep the selected value for a dropdownlist after form submission in Cakephp?
If more info (or some code) is needed just tell me please.
UPDATE
Here is part of the code in my view:
echo $this->Form->create('Chart');
echo $this->Form->input('username',
array('label'=>('Usernames List'),
'default'=>('Select username'),
'options'=>$usernames, 'selected'=>false));
echo $this->Form->end('Create Chart');
So, when I press 'Create Chart', the dropdownlist doesn't keep the username that I selected, but it goes back to the first one.
The Form helper uses the data stored in $this->data to prepopulate fields. Make sure that when you are submitting the form, the view that is rendered after has the appropriate model/key data stored in $this->data in order for the Form helper to correctly fill in the appropriate values.
Can we see your controller action possibly? That may help draw a more accurate conclusion.
you should never use the view to set defaults or values (especially selected/value is wrong as it - like your code - destroys the idea of persistent forms).
use the controller instead
#see http://www.dereuromark.de/2010/06/23/working-with-forms/ (Default Values)
add value in dropdown like this:
<?php echo $this->form->select('Schedule.showsid', array('0'=>'title', '1'=>'description'));?>

dropdown list atk4 quicksearch

i try to populate a dropdown menu for quicksearch in mvcgrid my code is:
$g = $this->add('MVCGrid');
$g->setModel('materiale');
$g->addPaginator(25);
$s = $g->addQuickSearch(array('nome_mat'));
$value_list = array(
1=>'Granito',
2=>'Marmo'
);
$s->addField('dropdown','tipo_mat','Tipo_mat: ')->setValueList($value_list);
The dropdown list appear on quick search form.
My db field is tipo_mat, but when i click quicksearch button nothing uppens, can someone help me plase.
Thank's
You will find that the Quicksearch is nothing more that a simple form, which applies condition to your grid when submitted. In theory, you could have a standard form sitting in there doing the same thing:
$search = $g->add('Form',null,'quick_search',array('form/quicksearch','form'));
$search->addFiled('dropdown','tipo_mat')
->setValueList($value_list)
->set($_GET['tipo_mat']);
$search->addField('search','q')
->set($_GET['q']);
// Handle submit of form, reload grid with AjAX, pass values as arguments
if($search->isSubmitted()){
$grid->js()->reload($search->getAllData())->execute();
}
// If values are passed, use them
if($_GET['q'])
$grid->dq->where('name like','%'.$_GET['q'].'%');
if($_GET['tipo_mat'])
$grid->dq->where('foo',$_GET['tipo_mat']);
The "Filter" and "QuickSearch" classes help you with saving search values but you must not be afraid to look into their source and create your own QuickSearch class which can apply parameters properly.
Perhaps using Filter in your case is better than quick search, because of how "applyDQ" is handled:
https://github.com/atk4/atk4/blob/master/lib/Filter.php#L62

CakePHP form helper - change value of hidden input for checkbox/radio

Using CakePHP's form helper to generate a checkbox is easy enough; to use the example from the documentation:
echo $this->Form->checkbox('done',array('value' => 555));
This will produce the following HTML:
<input type="hidden" name="data[User][done]" value="0" id="UserDone_" />
<input type="checkbox" name="data[User][done]" value="555" id="UserDone" />
This is all well and good, and the hidden field serves to force submission of a value for the "done" field even if the box remains unchecked.
Now, for the sake of argument, let's say the database definition of this field is ENUM('yes','no'). Of course I can easily change the value of the checkbox to "yes". However, if it's unchecked, a value of "0" is submitted from the hidden element. This produces no error or warning from mysql, as 0 is always a legal value for an enum field; it appears as an empty string.
Can I change value of the hidden field that CakePHP generates (to "no"), or do I need to suppress the auto-generation and create the hidden field myself? (An annoyance that grows with the number of checkboxes.)
I believe this all applies to radio button groups, too—at least if they don't have a default selection.
I'm using CakePHP 1.3. Thanks.
With FormHelper::checkbox, you can use hiddenField to set the default value.
<?php echo $this->Form->checkbox('done', array('value'=>'yes', 'hiddenField'=>'no');?>
With FormHelper::radio, you can only set value to default to one of the options, if the values match. This will also suppress the hidden field.
<?php echo $this->Form->radio('done', array('yes' => __('Yes')), 'no' => __('No'), array('value'=>'no');?>
Also, you should remember that CakePHP does not support enums (and I am sure this sort of scenario is one reason)
If your field data is truly binary (yes/no true/false enables/disabled etc.) then for the sake of CakePHP conventions you should just use an int(1) or tinyint(1) field and then convert the boolean value to yes/no etc in the view.
Then you don't have to worry about creating your own hidden input values and disabling the generated hidden inputs.
Another option would be to override the form->helper checkbox method that gets called by form->input to accept a new key in the options array that sets the value to something other than a 0 / false.
Unfortunately, FormHelper::checkbox allows you to disable the hidden element, but not to select its value, so you will need to do so and create the hidden field yourself. For example:
<?php echo $this->Form->hidden('done',array('value'=>'no'))?>
<?php echo $this->Form->checkbox('done',array('value'=>'yes','hiddenField'=>false))?>
With FormHelper::Radio worked for me like that
echo $this->Form->radio(
'done',
['yes' => __('Yes'), 'no' => __('No')],
['hiddenField' => false]
);

Resources