【问题标题】:Laravel form with placeholder, class and input::old带有占位符、类和输入的 Laravel 表单::old
【发布时间】:2014-11-21 09:26:48
【问题描述】:

我正在努力适应 Laravel 的刀片。

我想创建一个名为 company 的文本输入。

输入字段需要有一个id和一个类。

如果数据库中没有数据,或者存储的数据已经存在,我还想显示一个占位符。

最后,我想保留引入的输入以防出错。

我想在此使用类似的东西:

{{ Form::text(
  'company',
  isset($user->company)?$user->company:array('placeholder'=>'Your company'),
  array('class' => 'field required', 'id' => 'company'),
  Input::old('company')
) }}

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: forms laravel


    【解决方案1】:

    Laravel 将为您处理重新填充输入,只要 POST 数据中的键与您输入的 name 属性相同。

    Form::text(),第一个参数是字段名,第二个参数是你想要的默认值,第三个参数是你想要设置的HTML属性数组。所以,你会:

    {{ Form::text('company', null, array(
        'class' => '',
        'id' => '',
        'placeholder' => '',
    )) }} 
    

    显然将classidplaceholder 值替换为您想要的值。

    【讨论】:

    • 如果我这样做,我不会从数据库中检索数据
    • 那你的表单或控制器有问题。正如我所说,如果名称匹配,Laravel 会自动将字段的值设置为 POST 数据中的任何内容。在您的控制器中尝试Redirect::to('url')->withInput();
    【解决方案2】:

    简单的方法,使用form model binding

    {{ Form::model($user, [ ...options...]) }}
    
     {{ Form::text(
       'company',  // refers to $user->company
        null,      // auto populated with old input in case of error OR $user->company
        array('class' => 'field required', 'id' => 'company',
        'placeholder' => 'Your company')  // placeholder is html attribute, don't use model data here
     ) }}
    

    如果您不想要表单模型绑定,这就是您所需要的:

     {{ Form::text(
       'company',
        $user->company, // auto populated with old input in case of error
        array('class' => 'field required', 'id' => 'company',
        'placeholder' => 'Your company')
     ) }}
    

    【讨论】:

      【解决方案3】:

      找到了!

      如果我这样做,对我来说效果很好:

      {{ Form::text( 
        'company', 
        Input::old( 'company', $user -> company ) , 
        array( 'class' => 'field required', 'id' => 'company', 'placeholder' => 'Your company' ) 
      ) }}
      

      【讨论】:

      • 你根本不需要Input::old()。 Laravel 会为您执行此操作,只要您在控制器中使用 Redirect()->withInput(),就像在我的回答中一样。
      猜你喜欢
      • 2011-06-01
      • 2018-11-03
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 2013-03-07
      • 2013-05-02
      相关资源
      最近更新 更多