在下拉列表HTML中设置默认选项

时间:2019-03-15 22:13:30

标签: php laravel

在我的 create.blade.php 中,我有一个类似的下拉列表。

<div class="form-group">
<label for="company-content">Sexe</label>
<select name="sex" id="" class="form-control">
<option value="">Choice</option>
<option>Women</option>
<option>Man</option>
</select>
</div>

如果我选择选项2,即项目 man ,则希望在我的 edit.blade.php 中获得项目 man enter image description here

但是,当我要更改项目时,默认情况下,我的下拉列表始终位于 woman 上。这不现实...

这是我有关edit.blade.php文件的代码,请问您有什么主意吗?

谢谢

enter image description here

<div class="form-group">
<label for="company-content">Sex</label>
<select name="sexe" id="" class="form-control">
<option>Women</option>
<option>Man</option>
</select>
</div>

编辑: 2019年3月16日

显然,我也应该在Controller上做几处修改?

我的功能编辑

public function edit($id)
{
        //
  $candidats = Candidat::find($id);
  $permis = Permis::all();
  return view('admin.candidats.edit', compact('candidats', 'permis'));
}

我的功能更新

public function update(Request $request, $id)
{
     $request->validate([
           'sexe' => 'required|string',
           'fk_permis' => 'required'
    ]);

      $candidats = Candidat::find($id);
      $candidats->sexe = $request->get('sexe');
      $candidats->fk_permis = $request->get('fk_permis');
      $candidats->save();
        return redirect()->route('candidats.index')
                    ->with('success', 'mise à jour effectuée');
    }

请在哪里添加此行?

return view('admin.candidats.edit', ['data' => $data]);

这是我的 edit.blade.php

<div class="form-group">
  <label for="company-content">Sex</label>
  <select name="sexe" class="form-control" >
  <option value="Man"  {{ $data['sexe'] == "Man" ? 'selected="selected"' : '' }}>Man</option>
   <option value="Women" {{ $data['sexe'] == "Women" ? 'selected="selected"' : '' }}>Women</option>
    </select>
</div>

那么,我的问题出在我的控制器上吗?

2 个答案:

答案 0 :(得分:1)

假设您要以表单形式发布数据,并且包含@ Second2None建议的值,则需要告诉表单选择相关选项。

<option<?php if ($_POST['sexe'] == 'man') echo " selected"; ?>>Man</option>

答案 1 :(得分:1)

对于控制器返回视图中的laravel,具有类似数据

return view('edit', ['data' => $data]);

<select name="sexe" class="form-control" >
        <option value="Man"  {{ $data['sexe'] == "Man" ? 'selected="selected"' : '' }}>Man</option>
          <option value="Women" {{ $data['sexe'] == "Women" ? 'selected="selected"' : '' }}>Women</option>
        </select>

和php

<select name="sexe" class="form-control" >
        <option value="Man"  {{ $_GET['sexe'] == "Man" ? 'selected="selected"' : '' }}>Man</option>
          <option value="Women" {{ $_GET['sexe'] == "Women" ? 'selected="selected"' : '' }}>Women</option>
        </select>
相关问题