2016-02-15 19 views
0

我正在使用laravel 5.2並希望驗證編輯表單中的某些數據。我的目標應該是顯示錯誤並在輸入字段中保留錯誤的數據。Laravel - 如何處理PUT表單上的錯誤?

我的問題是,輸入由ContentRequest驗證和FormRequest回報

$this->redirector->to($this->getRedirectUrl()) 
           ->withInput($this->except($this->dontFlash)) 
           ->withErrors($errors, $this->errorBag); 

這是罰款爲止。下一步調用控制器中的edit操作並覆蓋所有參數。

我已經做了目前:

ContentController

public function edit($id) 
{ 
    $content = Content::find($id); 

    return view('contents.edit', ['content' => $content]); 
} 

public function update(ContentRequest $request, $id) 
{ 
    $content = Content::find($id); 

    foreach (array_keys(array_except($this->fields, ['content'])) as $field) { 
     $content->$field = $request->get($field); 
    } 
    $content->save(); 

    return redirect(URL::route('manage.contents.edit', array('content' => $content->id))) 
     ->withSuccess("Changes saved."); 
} 

ContentRequest

class ContentRequest extends Request 
{ 
    public function authorize() 
    { 
     return true; 
    } 
    public function rules() 
    { 
     return [ 
      'title' => 'required|min:3', 
      'body' => 'required|min:3' 
     ]; 
    } 
} 

我該如何解決這個問題?該形式如下:

<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}" 
      id="site-form" class="form-horizontal" method="POST"> 
     {!! method_field('PUT') !!} 
     {!! csrf_field() !!} 

     <div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}"> 
      <label for="title" class="col-sm-2 control-label">Title</label> 

      <div class="col-sm-10"> 
       <input type="text" class="form-control" name="title" id="title" placeholder="Title" 
         value="{{ $content->title }}"> 

       @if ($errors->has('title')) 
        <span class="help-block"> 
         <strong>{{ $errors->first('title') }}</strong> 
        </span> 
       @endif 
      </div> 
     </div> 
    </form> 
+0

你是如何構建表單的? –

回答

2

嘗試類似如下:

<input 
type="text" 
class="form-control" 
name="title" 
id="title" 
placeholder="Title" 
value="{{ old('title', $content->title) }}" /> 

注意value屬性。也check the documentation和發現Retrieving Old Data

+0

謝謝,該解決方案 – mc388

+0

最受歡迎:-) –