【问题标题】:Laravel alternative value for input if Input::old is empty如果 Input::old 为空,Laravel 的输入替代值
【发布时间】:2014-04-29 06:41:07
【问题描述】:

如果旧值为空,Laravel 中是否有任何实用函数允许您为特定输入字段提供替代值?目前我有以下代码:

<input type="text" class="form-control" id="title" name="title" value="{{ (!empty(Input::old('title'))) ? Input::old('title') : 'hey' }}">

但它并不是真的那么漂亮。有什么想法吗?

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    使用

    Input::old('title', 'fallback value')
    

    【讨论】:

      【解决方案2】:

      是的!不要使用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 内置了所有这些,而且您可以免费获得!使用请求、验证器、刀片/HTML

      【讨论】:

        猜你喜欢
        • 2014-05-28
        • 1970-01-01
        • 2016-10-09
        • 2013-09-21
        • 2013-06-08
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多