【发布时间】:2016-07-03 04:54:53
【问题描述】:
在我使用的输入字段后显示验证错误:
<div class="form-group">
{!! Html::decode(Form::label('first_name','First Name:<span class="required">*</span>',['class'=>'control-label col-sm-3'])) !!}
<div class="col-sm-6">
{!! Form::text('first_name',null,['class'=>'form-control']) !!}
@if ($errors->has('first_name'))
<span class="help-block">
<strong>{{ $errors->first('first_name') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
{!! Html::decode(Form::label('last_name','Last Name:<span class="required">*</span>',['class'=>'control-label col-sm-3'])) !!}
<div class="col-sm-6">
{!! Form::text('last_name',null,['class'=>'form-control']) !!}
@if ($errors->has('last_name'))
<span class="help-block">
<strong>{{ $errors->first('last_name') }}</strong>
</span>
@endif
</div>
</div>
// and so on......
此代码完美运行。但是我必须在每个输入框中编写几乎相同的代码。所以,我打算做一个全局函数来显示错误。为此,我执行了以下操作。
- 在
app文件夹中创建一个helpers.php -
编写以下代码:
function isError($name){ if($errors->has($name)){ return '<span class="help-block"><strong>'.$errors->first($name).'</strong></span>'; } } 运行
composer dump-autoload-
这样在刀片文件中使用它:
<div class="form-group"> {!! Html::decode(Form::label('first_name','First Name:<span class="required">*</span>',['class'=>'control-label col-sm-3'])) !!} <div class="col-sm-6"> {!! Form::text('first_name',null,['class'=>'form-control']) !!} {{ isError('first_name') }} </div> </div> <div class="form-group"> {!! Html::decode(Form::label('last_name','Last Name:<span class="required">*</span>',['class'=>'control-label col-sm-3'])) !!} <div class="col-sm-6"> {!! Form::text('last_name',null,['class'=>'form-control']) !!} {{ isError('last_name') }} </div> </div>
现在,当我转到 create.blade.php 时出现错误
未定义变量:错误(查看:D:\xampp\htdocs\hms\resources\views\guest\create.blade.php)
我知道问题出在helpers.php,因为我没有定义$errors,我只是从刀片文件中粘贴代码。
【问题讨论】:
-
$errors未在您的帮助程序中定义。您需要将错误对象传递给isError()函数。例如isError($errors, last_name'). -
@Jeemusu 好主意。我试试看。
-
@Jeemusu 是的,它奏效了。另外我更改了刀片
{!! isError($errors,'first_name') !!}以转义 html 标记。你能把它作为一个答案,以便我接受吗?
标签: laravel laravel-5 laravel-blade validationerror