【问题标题】:Create helpers function for displaying validation errors创建帮助函数以显示验证错误
【发布时间】: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......

此代码完美运行。但是我必须在每个输入框中编写几乎相同的代码。所以,我打算做一个全局函数来显示错误。为此,我执行了以下操作。

  1. app 文件夹中创建一个helpers.php
  2. 编写以下代码:

    function isError($name){
        if($errors->has($name)){
            return '<span class="help-block"><strong>'.$errors->first($name).'</strong></span>';
        }
    }
    
  3. 运行composer dump-autoload

  4. 这样在刀片文件中使用它:

    <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


【解决方案1】:

问题在于 $errors 变量在您的辅助方法范围内未定义。

这可以通过将$errors 对象传递给isError() 辅助方法来轻松解决。

助手

function isError($errors, $name){
    if($errors->has($name)){
        return '<span class="help-block"><strong>'.$errors->first($name).'</strong></span>';
    }
}

刀片模板

{!! isError($errors, 'first_name') !!}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-23
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多