我创建了一个创建表单,并在其中创建了一个下拉列表,该下拉列表由数据库中表中的元素动态填充,问题是下拉列表中选定的项目未将其值传递给控制器,并且验证警报不断显示,它的下拉列表是必填字段(考虑未选中),我删除了验证标签,并收到一条SQL错误,指出我的下拉列表传递了null(db中的非null字段),这是html片段下拉列表
<form method="post" action="{{ route('interventions.store') }}">
<div class="form-group">
@csrf
<label for="name">Type Intervention:</label>
<select class="form-control" name="type">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=gestionpreventionincendie', 'root', '');
$sql = "SELECT * FROM type_intervs";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$types = $stmt->fetchAll();
foreach($types as $type): ?>
<option value="<?= $type['id']; ?>">
<?= $type['type']; ?></option>
<?php endforeach; ?>
</select><br/>
<label for="com">Commentaire:</label>
<input type="text" class="form-control" name="commentaire"/>
</div>
<button type="submit" class="btn btn-primary">Confirmer</button>
</form>
这是控制器中的存储方法
public function store(Request $request)
{
$request->validate([
]);
$user = Auth::user();
$intervention = new Intervention([
'type' => $request->get('type'),
'commentaire' => $request->get('commentaire'),
'user' => $user['email']
]);
$intervention->save();
return redirect('/interventions')->with('success', 'Intervention Ajouté');
}
答案 0 :(得分:2)
尝试为您的选项添加名称
<select class="form-control" name="type">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=gestionpreventionincendie', 'root', '');
$sql = "SELECT * FROM type_intervs";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$types = $stmt->fetchAll();
foreach($types as $type): ?>
<option name="type" value="<?= $type['id']; ?>">
<?= $type['type']; ?></option>
<?php endforeach; ?>
</select><br/>