我有一个通过一些验证的 Laravel 表单。显然,如果验证失败,我希望用户被重定向到表单并警告他们的错误。此外,由于表单相当大,我不希望用户必须重新输入任何数据。这是表格(我已经剪掉了很大一部分以减小此消息的大小)
:@layout('templates.main')
@section('content')
@if(Session::has('validation_errors'))
<ul class="form_errors">
@foreach($errors as $error)
{{$error}}
@endforeach
</ul>
@endif
{{ Form::open('account/create', 'POST') }}
<table>
<tr>
<td>{{ Form::label('dealer', 'Dealer') }}</td>
<td>{{ Form::select('dealer', array('1' => 'Dealer #1', '2' => 'Dealer #2')) }}</td>
<td>{{ Form::label('amount', 'Amount') }}</td>
<td>{{ Form::text('amount', Input::old('amount')) }}</td><!--Here is where I'm testing for old input-->
</tr>
<tr>
<td>{{ Form::label('date', 'Date') }}</td>
<td>{{ Form::date('date', NULL, array('class' => 'date_picker')) }}</td>
<td>{{ Form::label('installation', 'Installation #') }}</td>
<td>{{ Form::input('text', 'installation') }}</td>
</tr>
<tr>
<td colspan="4">{{ Form::textarea('notebox', NULL, array('id' => 'notebox')) }}</td>
</tr>
<tr>
<td colspan="4">{{ Form::submit('Submit') }} {{ Form::reset('Reset') }}</td>
</tr>
</table>
{{ Form::close() }}
@endsection
提交表单后,这里是处理它的控制器:
public function post_create() {
//Validate it in the model
$validation = Account::validate(Input::all());
if($validation->fails()){
return Redirect::to('account/create')
->with_input()
->with('validation_errors', true)
->with('errors', $validation->errors->all('<li>:message</li>'));
}
else {
return "passed";//for debugging purposes
}
}
最后,这是 Account 模型:
class Account extends Eloquent {
public static function validate($input) {
//Validation rules
$rules = array(
'firstname' => 'required',
'lastname' => 'required',
//etc...
);
//Custom validation messages
$messages = array(
'firstname_required' => 'A first name is required.',
'lastname_required' => 'A last name is required.',
//etc...
);
//Pass it through the validator and spit it out
return Validator::make($input, $rules, $messages);
}
}
因此,当我通过故意使表单无效来进行测试时,我被重定向到帐户/创建表单,但是,没有显示验证错误,并且没有保存旧输入(我只附加Input::old()
到金额文本框)。