我已经为类别和子类别创建了一个下拉列表。它在我提交表单时工作正常,但是当我编辑表单时,类别字段没有来自数据库的重新填充数据,类别下拉就像它在创建表单中显示一样。
这是我的编辑:
<div class="form-group">
{!! Form::label('category','Category:') !!}
<select name="category" id="category" class="form-control input-sm">
@foreach($s as $k)
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
@endforeach
</select>
</div>
<div class="form-group">
{!! Form::label('subcategory','Subcategory:') !!}
<select name="subcategory" id="subcategory" class="form-control input-sm">
<option value=""></option>
</select>
</div>
控制器:
public function edit($id)
{
// get the event
$event = Event::findOrFail($id);
$s = Category::all()->where('parent_id','=','0');
$r = Event::all();
$daysOfWeek = unserialize(Event::find($id)->days_of_week);
// show the edit form and pass the event
return view('event.edit',compact('event','s','r','daysOfWeek'));}
我还没有使用下拉列表的关系,我选择了类别后使用了jquery和ajax来选择子类别。 当我编辑表单时,如何才能将值存储在数据库中?
答案 0 :(得分:1)
我得到了答案,感谢每一个人的帮助!
查看:
<div class="form-group">
{!! Form::label('category','Category:') !!}
<select name="category" id="category" class="form-control input-sm">
@foreach($s as $k)
@if($k['id'] == $m)
<option value="{{ $k['id'] }}" selected="{{$m}}">{{ $k['name'] }}</option>
@else
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
@endif
@endforeach
</select>
</div>
<div class="form-group">
{!! Form::label('subcategory','Subcategory:') !!}
<select name="subcategory" id="subcategory" class="form-control input-sm">
@foreach($subcat as $k)
@if($k['name'] == $subid)
<option value="{{ $k['id'] }}" selected="{{$subid}}">{{ $k['name'] }}</option>
@else
<option value="{{ $k['id'] }}">{{ $k['name'] }}</option>
@endif
@endforeach
<option value=""></option>
</select>
</div>
控制器:
public function edit($id)
{
$event = Event::findOrFail($id);
$s = Category::where('parent_id','=','0')->get();
$r = Event::all();
$m = Event::find($id)->category;
$subid = Event::find($id)->subcategory;
$subcat = Category::where('parent_id','=',$m)->get();
$daysOfWeek = unserialize(Event::find($id)->days_of_week);
return view('event.edit',compact('event','s','subcat','subid','r','daysOfWeek','m'));
}
答案 1 :(得分:0)
您的控制器方法edit()
您的密码:
$s = Category::all()->where('parent_id','=','0'); // wrong
不应该是:
$s = Category::where('parent_id','=','0')->get(); // correct
您已经使用all
获取类别,然后传递where
条件,因此它不会显示结果。 where
条件会返回instance
Illuminate\Database\Eloquent\Builder
而非预期结果。
使用正确的行更新错误的行,结果应按您的意愿显示。
希望这会帮助你。快乐的编码。欢呼声。