[英]Laravel/php - creating an array of boolean values from multiple checkboxes
I"m attempting to create an array of a user's selections from 4 checkboxes, where the values are boolean (1 or 0). Here's where I'm at so far: 我正在尝试从4个复选框创建用户选择的数组,其中的值为boolean(1或0)。这是我到目前为止的位置:
$selections = [
'marketing' => $request->get('marketing'),
'promotional' => $request->get('promotional'),
'news' => $request->get('news'),
'feedback' => $request->get('feedback')
];
foreach ($selections as $selection) {
if ($selection === null) {
return $selection = 0);
}
}
dd($selections);
Trying to foreach through and check if the checkbox was deselected(null) and set that to zero. 尝试遍历并检查复选框是否未选中(空)并将其设置为零。 I don't think I can do this in my form, but here's that code as well just in case:
我不认为可以在表单中执行此操作,但是为了以防万一,这里也提供了以下代码:
<div class="form-group col-sm-12">
<label>Uncheck the categories you would like to not receive emails from.</label>
<div class="checkbox">
<br/>
<label>
{{ Form::checkbox('marketing', '1', true) }}
Marketing</label>
</div>
<div class="checkbox">
<br/>
<label>
{{ Form::checkbox('promotional', '1', true) }}
Promotional</label>
</div>
<div class="checkbox">
<br/>
<label>
{{ Form::checkbox('news', '1', true) }}
News</label>
</div>
<div class="checkbox">
<br/>
<label>
{{ Form::checkbox('feedback', '1', true) }}
Feedback</label>
</div>
</div>
Answer migrated from comment 答案已从评论迁移
The problem here is the lack of a default value. 这里的问题是缺少默认值。
The $request->get()
function call will return null
if the value is not in the request which is the case for a unchecked checkbox. 如果
$request->get()
中没有该值,则$request->get()
函数调用将返回null
,这是未选中复选框的情况。
One solution for this problem is the ??
解决此问题的一种方法是
??
operator in php. PHP中的运算符。
$request->get('marketing') ?? 0
This essentially says "Take the value of 'marketing', if it is not defined use the value 0
". 本质上说:“如果没有定义,则使用'marketing'的值,请使用值
0
“。
It's a practical way for update and create of check boxes and switch buttons which works perfectly on our website 这是一种更新和创建复选框和切换按钮的实用方法,在我们的网站上可以完美运行
<label>
@if($model->exists)
<!--on edit-->
<input type="checkbox" name="active" {{$model->active ? 'checked value="1"' : 'value="0"'}}>
@else
<!--on create-->
<input type="checkbox" name="active" checked value="{{old('active', 1)}}">
@endif
</label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.