2017-08-28 55 views
0

我在Laravel中創建了一個編輯表單,並且我想選擇Select Dropdown中的選定(數據庫)值。我現在正在做如下。正確的方法或更好的方法是可能的嗎?我正在使用Laravel 5.4。Laravel編輯表單 - 選擇默認選項

<select class="form-control" id="type" name="type"> 
    <option value="admin" @if($user->type==='admin') selected='selected' @endif>Admin</option> 
    <option value="telco" @if($user->type==='telco') selected='selected' @endif>Telco</option> 
    <option value="operator" @if($user->type==='operator') selected='selected' @endif>Operator</option> 
    <option value="subscriber" @if($user->type==='subscriber') selected='selected' @endif>Subscriber</option> 
</select> 

回答

1

我會說這是一個正常的方法。

如果你想讓它更「友好」,將使用@foreach循環來,將創建的選擇,像這樣所有選項的數組需要一定的開銷,例如:

$arr = ['admin','telco','operator','subscriber']; 

@foreach($arr as $item) 
    <option value="{{ $item }}" @if($user->type=== $item) selected='selected' @endif> {{ strtoupper($item) }}</option> 
@endforeach 
+0

這是有道理的! – Mohammad

0

您還可以使用三元運算符,而不是if

<select class="form-control" id="type" name="type"> 
    <option value="admin" {{($user->type ==='admin') ? 'selected' : ''}}> Admin </option> 
    <option value="telco" {{($user->type ==='telco') ? 'selected' : ''}}> Telco </option> 
    <option value="operator" {{($user->type ==='operator') ? 'selected' : ''}}> Operator </option> 
    <option value="subscriber" {{($user->type ==='subscriber') ? 'selected' : ''}}> Subscriber </option> 
</select>