微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在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 举报,一经查实,本站将立刻删除。