Laravel中是否有任何实用函数允许您在旧值为空的情况下为特定输入字段提供替代值?目前我有以下代码:
<input type="text" class="form-control" id="title" name="title" value="{{ (!empty(Input::old('title'))) ? Input::old('title') : 'hey' }}">
但它并没有那么漂亮。有什么想法吗?
使用
Input::old('title', 'fallback value')
是!不要使用input
标签:)
如果你使用{{ Form
,你会得到这个,还有更多!
{{ Form::text('email', null, array('class'=>'form-control', 'placeholder'=>'Email Address')) }}
查看此处的文档(http://laravel.com/docs/html&http://laravel.com/docs/requests)您会注意到,当输入闪存到会话时,blade渲染的这个输入框将自动用会话中的闪存值替换"null"(第二个参数)。
这样就不需要检查旧的输入,也不需要在模板中进行任何讨厌的if/else检查。此外,您不再需要担心任何HTML代码注入或XSS的发生,因为Form::text将确保文本正确转换为HTML实体。
在检查错误的地方,应该使用Laravel验证器。类似的东西:
protected function createUser(){
$rules = array(
'email'=>'required|email',
'password'=>'required|min:6|confirmed',
'password_confirmation'=>'required'
);
$validator = Validator::make(Input::all(), $rules);
if (! $validator->passes()) {
Input::flashExcept('password', 'password_confirmation');
return Redirect::to('my_form');
} else {
// do stuff with the form, it's all good
}
return Redirect::intended('/complete');
}
此外,在您的模板中,您可以显示表单中的所有错误:
<ul>
@foreach($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
或者只需选择第一个错误并将其显示在{{ Form::text
下
@if ($errors->has('first_name'))
<span class="error">{{$errors->first('first_name')}}</span>
@endif
Laravel内置了所有这些,你可以免费获得!使用请求、验证器、Blade/HTML