2016-02-01 85 views
4

虛假的形式,我有多種選擇如何在驗證返回laravel 5

<div class="form-group"> 
        <label>Seasons</label> 
        <select class="form-control" name="year_code" required> 
         <option value="{{ Input::old ('year_code') }}" 
           selected>{{ Input::old ('year_code') }}</option> 
         <div class="divider"></div> 
         <option value="16">2016-2017</option> 
         <option value="17">2017-2018</option> 
         <option value="18">2018-2019</option> 
         <option value="20">2020-2021</option> 

        </select> 
       </div> 

如果驗證失敗,因爲錯誤的值(PHP端驗證)的得到的期權價值的名 我的形式返回與舊的輸入,可以說季2016-2017被選中 如果我的表單失敗返回值將是16,它會顯示。 我可以做多個if語句像

@if(\Input::get(year_code) == 16) 
show 2016-2017 
@elseif (\Input::get(year_code) == 17) 
show 2017-2018 
... 
@endif 

,但我正在尋找更有效的方式來獲得一個值的名稱。

回答

3

而不是硬編碼,讓他們在一個多維數組,使您可以更容易操作。

$arr = [ 
    ["value" => 16, "text" => "2016-2017"], 
    ["value" => 17, "text" => "2017-2018"], 
    ["value" => 18, "text" => "2018-2019"] 
    ... 
]; 

通過ViewComposer將數據傳遞給您的視圖。

@foreach($arr as $entry) 
    @if((int) Input::old('year_code') === $entry['value']) 
     <option value="{{ $entry['value'] }}" selected>{{ $entry['text'] }}</option> 
    @else 
     <option value="{{ $entry['value'] }}">{{ $entry['text'] }}</option> 
    @endif 
@endforeach 

另外,好像值可以被自動生成。我會親自創建一個看起來像這樣的日期迭代器。 (僞)

public function getYears(int $diff): array { 
    $start = Date::today()->startOfYear(); 
    $end  = Date::today()->addYears($diff)->startOfYear(); 
    $response = []; 

    $start->diffInYears($end, function ($year) use (&response) { 
     $response[] = sprintf("%s - %s", $year->format("Y"), $year->addYear()->format("Y")); 
    }); 

    return $response; 
} 
0
<div class="form-group"> 
<label>Seasons</label> 
<select class="form-control" name="year_code" required> 
    <option value="16" {{\Input::get(year_code)==16?'selected':''}}>2016-2017</option> 
    <option value="17" {{\Input::get(year_code)==17?'selected':''}}>2017-2018</option> 
    <option value="18" {{\Input::get(year_code)==18?'selected':''}}>2018-2019</option> 
    <option value="20" {{\Input::get(year_code)==20?'selected':''}}>2020-2021</option> 

</select> 
</div> 
+0

有在這種情況下,我認爲我找的efficent方式可能在某種程度上獲得與取決於值的JavaScript名三元語句之間,如果沒有什麼區別。 –