【发布时间】:2020-08-04 18:43:20
【问题描述】:
目前,我正在为子类别工作一个项目选择选项下拉列表
选择选项下拉列表是来自另一个表的外键
目标控制器
public function create()
{
$categories = GoalType::with('children')->whereNull('parent_id')->get();
$goal = new Goal();
return view('goals.create')
->with('goal', $goal)
->with('categories', $categories)
;
}
目标模型
class Goal extends Model
{
protected $fillable = [
'id',
'goal_type_id',
'goal_title
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
目标类型模型
class GoalType extends Model
{
protected $fillable = [
'name',
'parent_id',
];
public function children()
{
return $this->hasMany('App\Models\GoalType', 'parent_id');
}
public function parent()
{
return $this->hasOne(App\Models\GoalType::class, 'id', 'parent_id');
}
}
查看
<select id="goal_type" class="form-control @error('goal_type_id') is-invalid @enderror" name="goal_type_id">
<option value="">Select Goal Type</option>
@foreach ($categories as $category)
@if ($category->children)
@foreach ($category->children as $child)
@unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id', $goal->goal_type_id) ? 'selected' : '' }}> {{ $child->name }}</option>
@endunless
@endforeach
@endif
@endforeach
</select>
在上面的视图刀片中,我尝试将 old() 辅助函数应用于选择选项下拉列表,以便在提交后出现验证错误时它会保留其值。
我观察到它不起作用。下拉列表中的数据被清除。
我该如何解决这个问题?
谢谢
【问题讨论】:
-
也请考虑投票?
标签: laravel