我有下面的表格供用户选择他想要的每种注册类型的数量。
例如,如果会议具有两种注册类型(例如:general和plus),则用户可以选择他想要注册类型“general”的数量“1”和注册类型“plus”的数量“1”。如果用户进行此选择,他会进入注册页面,它可以正常工作。
但是如果用户没有为任何注册类型选择任何数量而不是出现验证错误,则显示“Undefined variable: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]));
}
注册类型数量规则:
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之间选择一个值。
注册类型表的列中的主要参与者,并且表示用户可以为注册选择的最小数量。
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之间。
你需要在foreach之前添加
$selectedRtypes = [];
而你在Session::put('customQuestions', $selectedRtypes[$rtype->name]['questions']);
可能有错误。循环将始终作为关键字的最后结果。
只有当$selectedRtypes
真实时,才在foreach循环中定义$quantity
。因此,只要您没有有效的$selectedRtypes
,就不会定义$quantity
。
在循环之外定义$selectedRtypes
,因为您依赖它定义,或验证输入数组以确保提供有效数量。
后者似乎是必要的,因为你还依赖于$rtype
,它也在循环内定义并依赖于有效的数量和类型。数量0似乎通过了验证,但是你的if ($quantity)
检查会失败。