如何在Livewire中更新多行 刀片视图组件

问题描述

我必须提供功能,使用户可以更新字段并添加更多内容,如果他们希望删除某些内容,可以这样做,但是我做不到,您可以在我的代码中看到我在更新功能内尝试通过$id检查来创建新记录,但是我不能这样做。如果尝试添加一些新记录,那么它会给我这个错误Undefined index: id,我在Laravel Playground创建了一个游乐场,您可以在这里进行测试,我也将示例放在这里

刀片视图

<fieldset>
   <label>Variation values *</label>
   @foreach ($values as $key => $value)
     <div class="{{ $loop->last ? '' : 'mb-2' }}" wire:key="{{ $key }}">

        <div class="input-group">
           <input type="text" wire:model.defer="values.{{ $key }}.value" class="form-control" placeholder="Variation value">


            <div class="input-group-append">
              @if ($loop->index === 0)
                <button wire:click.prevent="addRowForValue" class="btn btn-primary font-size-large" type="button">
                    +
                </button>
              @else
                <button wire:click.prevent="removeRowForValue({{ $key }})" class="btn btn-danger font-size-large" type="button">
                   -
                </button>
              @endif
            </div>

        </div>
       @error("values.{$key}.value")
          <span class="text-danger font-size-base">{{ $message }}</span>
       @enderror
    </div>
  @endforeach
</fieldset>

组件

public function update()
{
    $this->validate([
        'name' => "required|string|unique:variations,name,{$this->variation_id}",'values.*.value' => 'required|string',]);

    $variation = Variation::query()->findOrFail($this->variation_id);
    $variation->update(['name' => $this->name]);


    foreach ($this->values as $key => $value) {
        $id = $this->values[$key]['id'];
        $variationValue = VariationValue::query()->findOrFail($id);

        if (! $id) {
            $variation->values()->create([
               'value' => $this->values[$key]['value']
            ]);
        } else {
            $variationValue->update([
               'value' => $this->values[$key]['value']
            ]);
          }
     }


     session()->flash('message','Variation updated successfully.');

     $this->clearForm();

     $this->emit('closeModal');
}

Playground上查看完整的代码和示例

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...