【发布时间】:2018-08-01 01:44:03
【问题描述】:
我有下面的表格供用户选择他想要的每种注册类型的数量。
例如,如果会议有两种注册类型(例如:general 和 plus),用户可以选择他想要注册类型“general”的数量“1”和注册类型“plus”的数量“1”。如果用户做了这个选择,他会进入注册页面,它工作正常。
但是如果用户没有为无注册类型选择任何数量而不是出现验证错误,它会显示“未定义变量:selectedRtypes ”。
你知道RegistrationTypeQuantity自定义规则的错误在哪里吗?
存储用户为每种注册类型选择的数量的方法
public function storeQuantities(Request $request, $id, $slug = null)
{
$request->validate([
'rtypes' => ['required', 'array', new RegistrationTypeQuantity],
]);
$rtypeQuantities = $request->get('rtypes');
$total = 0;
foreach ($rtypeQuantities as $rtypeName => $quantity) {
if ($quantity) {
$rtype = RegistrationType::where('name', $rtypeName)->firstOrFail();
$price = $rtype->price;
$selectedRtypes[$rtype->name]['quantity'] = $quantity;
$selectedRtypes[$rtype->name]['price'] = $price;
$selectedRtypes[$rtype->name]['subtotal'] = $price * $quantity;
$total += $selectedRtypes[$rtype->name]['subtotal'];
$selectedRtypes[$rtype->name]['total'] = $total;
$selectedRtypes[$rtype->name]['questions'] = $rtype->questions;
$selectedRtypes[$rtype->name]['id'] = $rtype->id;
//dd($selectedRtypes);
}
}
Session::put('selectedRtypes', $selectedRtypes);
Session::put('customQuestions', $selectedRtypes[$rtype->name]['questions']);
Session::put('total', $total);
return redirect(route('conferences.registration',
['id' => $id, 'slug' => $slug]));
}
RegistrationTypeQuantity 规则:
public function passes($attribute, $value)
{
foreach($value as $key=>$v) {
// if $v is null
if ( is_null($v)) return false;
$rtype = RegistrationType::where('name',$key)->first();
// if there is no $rtype
if ( ! $rtype) return false;
if($v == 0)
return true;
// $rtype was found
if ( ($v < $rtype->min_participants || $v > $rtype->max_participants) )
return false;
}
return true;
}
如果用户没有选择任何数量
$rtypeQuantities = $request->get('rtypes');
dd($rtypeQuantities);
显示:
array:2 [▼
"general" => "0"
"plus" => "0"
]
在用户的选择菜单中,为每种注册类型选择数量,用户只能在 min_participants 和 max_participants 之间选择一个值。
min_participants 是registration_types 表的一列,表示用户可以为注册选择的最小数量。
max_participants 是registration_types 表的一列,表示用户可以为注册类型选择的最大数量。
因此,例如,如果注册类型“general”的 min_participants 为“0”且 max_participants 为“2”,则用户只能为注册类型“general”选择介于 0 和 2 之间的数量。
<select class="custom-select form-control rtype_name" id="rtype_{{ $rtype->id }}"
data-price="{{ $rtype->price }}"
name="rtypes[{{ $rtype->name }}]">
<option value="0">0</option>
@for ($i = $rtype->min_participants; $i <= $rtype-> max_participants; $i++)
<option value="{{ $i }}">{{ $i }}</option>
@endfor
</select>
因此自定义规则应该验证用户是否填写了选择菜单字段,因为它是必需的,并且用户引入的值介于 min_participants 和 max_participants 之间。
【问题讨论】: