How to pass a boolean value in Laravel from a form to the Database? - forms

I tried checkbox it passes on when the checkbox is clicked. Is there no way to pass a boolean value in laravel from a form in laravel ?..

Define an eloquent mutator like this in your model (\App\MyModelName.php):
public function setXXXAttribute($value)
{
$this->attributes['xxx'] = ($value=='on');
}
where "XXX" is the tame of the database column.
The attribute xxx will be set to true in case the value of the checkbox is 'on'

When submitting the Form give the checkbox a value of true. This will then be passed through the form data.
<input type="checkbox" name="checkbox_name" id="checkbox" value="true"/>

I used eloquent mutators in laravel to solve this...
public function setOpenTodayAttribute($value)
{
$this->attributes['open_today'] = ($value=='on')?($value=1):
($value=0);
}
if the value is on i,e checked $value=='on' it will be set to1which is
*boolean* else it will be set to 0 which is false

Add in your form
{!! Form::checkbox('checkbox_name', '1'); !!}
When the checkbox_name is clicked, you can get value from $request->all() array by 'checkbox_name'.
Or
$checked = $request->has('checkbox_name')

Do you mean Model's Attribute Casting?
https://laravel.com/docs/5.5/eloquent-mutators

I needed an actual true or false to be sent, because a validation method wouldn't accept true or nothing. Here is what I did.
<input type="hidden" name="myBoolean" value="0">
<input type="checkbox" name="myBoolean" value="1">
this above returns 0
if you check the checkbox, and the DOM looks like this
<input type="hidden" name="myBoolean" value="0">
<input type="checkbox" name="myBoolean" value="1" checked>
Now the second named element with the same name overwrites the first, and it returns 1.
litteral true/false would work as well
I''l be honest. I don't think this is a best practice approach. It is a quite clean easy to read, simple workaround though.

Related

Checkbox input remains false on form submit

I am trying to post a form and even though all the inputs map their value accordingly in the receiving controller-method , the bool-s of checkbox-es remain false.
What am i doing wrong ?
POCO
class MyPoco
{
public string User{get;set;}
public bool Require {get;set;}
}
Form
<form id="createForm" method="post" action="[some url]">
<input type="checkbox" id="require" name="Require" />
<input type="text" id="user" name="User"/>
</form>
Controller (method)
[HttpPost]
[Route("[some url]")]
public async Task<long> CreateAsync(MyPoco request)
{
}
Why in my case above does request.Require is always false.I have mapped them correctly (the name attribute).
The reason is that you forget to set value of checkbox:
<input type="checkbox" id="require" name="Require" value="true" />
If a checkbox is checked, then the postback values will contain a key-value pair of the form [InputName]=[InputValue]
If a checkbox is not checked, then the posted form contains no reference to the checkbox at all.
I see you are missing asp-for attribute for your checkbox input. Instead of name="Require", use asp-for="Require" as follows:
#model MyPoco
<input asp-for="Require" type="checkbox" id="require" />
If you don't want to use asp-for attribute then you have to use jQuery as follows:
$(document).on('change','#require',function() {
if ($(this).is(':checked')) {
$(this).val(true)
} else {
$(this).val(false)
}
});

Angular 5 - Disabling Radio Buttons

I have a radio button group in Angular 5. I want to disable some options, using the [disabled] attribute. However, I am noticing only the first radio button actually gets disabled. See my plunker: http://plnkr.co/edit/JzFmvjUyvhPdTkbYT1YZ?p=preview
Even if I hard code [disabled]="true", it still doesn't disable the second radio button. I don't want to switch to using a <select>, so I am curious if there is another way to get this to work with radio buttons.
There can be 2 solutions for this :-
1. Using the disabled attribute ([attr.disabled])
One solution to this problem can be using the disabled attribute ([attr.disabled]) instead of the disabled property ([disabled]), but [attr.disabled] works slightly differently, to enable the radio button you need to pass null to [attr.disabled] and any non-null value to disable it. Consider the below example :-
<input type="radio" name="enabled" [attr.disabled]="null" />Enabled1
<input type="radio" name="enabled" [attr.disabled]="null" />Enabled2
<input type="radio" name="disabled" [attr.disabled]="false" />Disabled1
<input type="radio" name="disabled" [attr.disabled]="false" />Disabled2
In this example the set of radio buttons named "enabled" will be enabled since for them [attr.disabled] is set to null, whereas the set of radio buttons named "disabled" will be disabled despite the [attr.disabled] being set to "false" this is because false is a non-null value.
2. Using fieldset tag
Another even better solution for this problem is using the <fieldset> tag for grouping the radio buttons together and then setting the [disabled] property on that <fieldset> tag instead of individual radio buttons. Below is an example for the same :-
<fieldset [disabled]=true>
<input type="radio" name="test" />yes
<input type="radio" name="test" />no
</fieldset>
Use this : (for reactive form approach)
<input
type="radio"
id="primaryIPV6"
value="2"
[attr.disabled]="flagValue ? '' : null"
formControlName="p_ip_type"
(change)="optionalFn()">
Set flagValue programmatically from .ts class:
use -> null : false (null would be interpreted as false )
use -> true/'' : true (true or simply blank would be interpreted as true)
One way to deal with the problem is to place the disabled binding on the last radio button in the group. Here is a modified version of your code: http://plnkr.co/edit/v6S5G7Do5NAMKzZvNdcd?p=preview
<input type="radio" name="answer" value="Yes" [(ngModel)]="name" /> Yes
<input type="radio" name="answer" value="No" [(ngModel)]="name" [disabled]="isDisabled()" /> No
There is a bug and a design problem in disabling (using [disabled]) Angular template driven radio buttons.
I fixed the bug in this pull request: https://github.com/angular/angular/pull/20310
The design problem is that we put the [disabled] binding on a single radio button, but it's all the group that is affected by the data binding. Here is a modified version of your code that illustrate the problem: http://plnkr.co/edit/3yRCSPsdjXqhUuU9QEnc?p=preview
It works fine like this [attr.disabled]="isDisabledState === true"
And in the component class you can have isDisabledState: boolean = true
I ended up cheating. Instead of using the same name for both radio buttons, I gave each radio button a unique name and bound them to the same backing field. http://plnkr.co/edit/zNbODcAqZMgjXfluxhW6?p=preview
#Component({
selector: 'my-app',
template: `
<form>
Hello {{name}}!!!
<input type="radio" name="answer1" value="Yes" [(ngModel)]="name" [disabled]="isDisabled1()" /> Yes
<input type="radio" name="answer2" value="No" [(ngModel)]="name" [disabled]="isDisabled2()" /> No
</form>
`,
})
export class App {
name:string;
isDisabled1(): boolean {
return false;
},
isDisabled2(): boolean {
return false;
}
}
Since they are both bound to the same backing field, they end up being mutually exclusive, behaving the way radio buttons should. It also allows them to be independently disabled.
In my real-world scenario, I actually only did one-way binding with (click) events to set the bound value, but it's the same trick.
I was working with ionic and the following works for me.
<ion-radio class="fix-radio_button" *ngIf="!IsSuspended" color="default" [disabled]="q.QuestionOptionId==q.AnswerId" [checked]="q.QuestionOptionId==q.AnswerId"></ion-radio>
Considering DrNio answer you should use attr.disabled and set value as [value]="'Yes'". This is because assigning as "Yes" makes angular to evaluate it as an expression instead of just a value.So your input element would be :
<input type="radio" name="answer" [value]="'Yes'" [(ngModel)]="name" [attr.disabled]="isDisabled()" />
Here is your updated running code and punker..
Update Plunker
#Component({
selector: 'my-app',
template: `
<form>
Hello {{name}}!!!
<input type="checkbox" name="dus" [(ngModel)]="isDisabled">
<input type="radio" name="answer" value="Yes" [(ngModel)]="name" [disabled]="isDisabled" /> Yes
<input type="radio" name="answer" value="NO" [(ngModel)]="name" [disabled]="isDisabled" /> No
</form>
`,
})
export class App {
name = 'Yes';;
isDisabled = true;
}
If you want to disable a specific radio button of angular material which is in a loop, you can do this based on specific condition. This can be done like this, using the disabled attribute of the radio group:
In HTML:
<mat-radio-group>
<mat-radio-button value="1"
[disabled]="name === 'welcome' ? false : true"
*ngFor="let name of names;">
{{ name }}
</mat-radio-button>
</mat-radio-group>
In .ts file:
public names = [
'welcome',
'computer',
'keyboard'
]

Remove an object from list of child objects in Model by checkbox unset in Fluid

I have two Extbase models with 1:n relation. Parent relates to Children via ObjectStorage.
What I want to achieve: editAction($parent) which shows a list of all Children as entries with a checkbox (checked by default). User is allowed to unset any checkbox, submit a form and corresponding Children should be removed from Parent relation.
What I've done so far.
In a fluid I iterate over objects and output the checkboxes like this:
<f:for each="{parent.children}" as="child" iteration="iteration">
<f:form.checkbox property="children.{iteration.index}" value="{child}" />
<label>{child.title}</label>
</f:for>
This generates following HTML, which seems okay for me:
<input type="hidden" name="tx_myext_plugin[parent][children][0][__identity]" value="">
<input type="checkbox" name="tx_myext_plugin[parent][children][0][__identity]" value="135" checked="checked">
<label>child0-title</label>
<input type="hidden" name="tx_myext_plugin[parent][children][1][__identity]" value="">
<input type="checkbox" name="tx_myext_plugin[parent][children][1][__identity]" value="136" checked="checked">
<label>child1-title</label>
...
But when I unset the 2nd checkbox (uid=136) and submit a form, I get the following Exception
#1297759968: Exception while property mapping at property path "children.1": The identity property "" is no UID.
Which also seems logical, because there is that hidden input, that submits an empty value.
I think, I can hook somewhere in MVC-process and just filter out the entries with empty __identity, but is there a more elegant (e.g. best practice) way?
TYPO3 7.6.11
In your controller, you can make an initialize*Action() function. There you can filter out your empty values so that only values with an identity exsist.
public function initializeSaveAction()
{
if ($this->request->hasArgument('parent')) {
$parent = $this->request->getArgument('parent');
foreach ($parent['children'] as $key => $child) {
if (!$child['__identity']) unset($parent['children'][$key]);
}
$this->request->setArgument('parent', $parent);
}
}
Now your saveAction is called after the initializeSaveAction and has only the selected children keept.

Spray - Parsing forms with checkboxes

I am setting up a simple API part of which accepts POST requests via form submission. The form requires the user to select one or more checkboxes all sharing the same name e.g.
<form>
<input type='text' name='textval'>
<input type='checkbox' name='cbox' value='val1'> Value 1
<input type='checkbox' name='cbox' value='val2'> Value 2
<button type='submit'>Submit</button>
</form>
I am attempting to handle the request in Spray like so:
path("mypath") {
post {
formFields('textval, 'cbox) { (textval, cbox) =>
// Now what?
}
}
}
I cannot find documentation in the Spray Docs on how to handle such inputs. In fact, this seemed to be an issue that has now been fixed, but I am unsure how to handle this form field with the Spray API
I have found a somewhat hacky solution to meet my needs. I have changed the names of my checkboxes to represent the values associated with them, and I use optional form fields in my spray route
Here is my new form
<form>
<input type='text' name='textval'>
<input type='checkbox' name='cbox1' value='val1'> Value 1
<input type='checkbox' name='cbox2' value='val2'> Value 2
<button type='submit'>Submit</button>
</form>
The route changes accordingly
path("mypath") {
post {
formFields('textval, 'cbox1.?, 'cbox2.?) { (textval, cbox1, cbox2) =>
complete(s"textval:'$textval', cbox1:'$cbox1', cbox2:'$cbox2'")
}
}
}
The optional fields get mapped to type Option[String] which can then be easily checked with .isEmpty or something similar to determine whether the checkbox was checked.
However, one issue is that it will allow forms to be posted with no checkboxes selected since they are all optional. You could perhaps set one as default.

Adding an extra relative value to an input value field

I'm currently creating a form that is very similar to the following code.
<form name="test" action="/go/test" method="post">
<input type=hidden name="hotspot_url" value="http://www.test.com/">
<input name="cky" value="<%write(cky);%>" type="hidden">
<input name="accept" value="Accept" type="hidden">
<input name="saccept" size="20" value="I Accept" onClick="hotspot.accept.value='Accept'" type="submit">
<input name="sdisconnect" size="20" value="I Decline" onClick="hotspot.accept.value='Decline'" type="submit">
</form>
However, the new form has a text input field. What I want to achieve is that the value entered in that text field is placed, upon send, after the test.com value (location marked with xxx)
<input type=hidden name="hotspot_url" value="http://www.test.com/xxx">
I've looked around - but i can't seem to find a solution.
What would be the best way to get this done?
You can use a buttons onclick event, which is not of type submit. When onclick occurs, you can first change the value of hidden field and then submit the form.
Or if you use JQuery, you can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
You can give both inputs an id, and do something like this:
give the form an "onsumbit= doThis()"
function doThis(){
var hiddeninput= $('#hiddeninput').val();
var input = $('#input').val();
$('#hiddeninput').val(hiddeninput+input);
return true;
}
this is very simple nothing fancy.