当使用Form :: model()和Form :: open()重用表单partial时,我遇到了如何使用默认值的问题。
例如,当使用以下形式partial partials / form.blade.php:
时{!! Form::text('myfield', 'Default') !!}
{!! Form::text('otherfield', '123') !!}
{!! Form::text('yetanother', 'Yet another default') !!}
// Etc
我将其包括如下,create.blade.php:
{!! Form::open() !!}
@include('partials/form.blade.php')
{!! Form::close() !!}
并编辑edit.blade.php:
{!! Form::model($mymodel) !!}
@include('partials/form.blade.php')
{!! Form::close() !!}
但是,无法使用默认值,因为edit.blade.php会忽略所有模型值(它始终是'默认',' 123&#39 ;和'又一个默认',而不是实际的模型值)。
当使用null作为默认值时,它将填充edit.blade.php的模型值,但是create.blade.php字段将为空。
在编辑和"默认"中使用模型值的好方法是什么?新模型的价值?
答案 0 :(得分:1)
您可以将默认值指定为数组,并使用Form::model()
作为创建表单:
{!! Form::model(['myfield' => 'Default', 'otherfield' => '123', 'yetanother' => 'Yet another default']) !!}
@include('partials/form.blade.php')
{!! Form::close() !!}
(如果还有更多字段我会从控制器传递默认值)
然后在form.blade.php
中使用无默认值:
{!! Form::text('myfield') !!}
{!! Form::text('otherfield') !!}
{!! Form::text('yetanother') !!}
如果$mymodel
直接来自控制器,您甚至可以使用相同的视图进行编辑和创建:
{!! Form::model($mymodel) !!}
{!! Form::text('myfield') !!}
{!! Form::text('otherfield') !!}
{!! Form::text('yetanother') !!}
{!! Form::close() !!}
只需在视图中注入正确的内容即可。像这样:
public function edit($id){
$mymodel = MyModel::find($id);
return view('form')->with('mymodel', $mymodel);
}
public function create(){
$defaults = [
'myfield' => 'Default',
'otherfield' => '123',
'yetanother' => 'Yet another default'
];
return view('form')->with('mymodel', $defaults);
}