【问题标题】:Laravel - old() helper function failed in Laravel child category select dropdownLaravel - old() 辅助函数在 Laravel 子类别选择下拉列表中失败
【发布时间】: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' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option>
                    @endunless
                    @endforeach
                  @endif
                @endforeach
              </select>

在上面的视图刀片中,我尝试将 old() 辅助函数应用于选择选项下拉列表,以便在提交后出现验证错误时它会保留其值。

我观察到它不起作用。下拉列表中的数据被清除。

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 也请考虑投票?

标签: laravel


【解决方案1】:
<option value="{{ $child->id }}" {{ (old("goal_type_id") == $child->id ? "selected":"") }}>&nbsp;&nbsp;{{ $child->name }}</option>

试试这个?

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 2020-08-14
    • 2020-07-30
    • 2022-08-04
    • 2020-06-14
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多