Форма редактирования встроенной таблицы livewire перестает отправлять запросы на сервер, когда она скрыта, и отображается только при нажатии кнопки редактирования

Я работаю над функциональностью редактирования встроенной таблицы компонентов в Laravel livewire, форма работает нормально, когда она отображается как обычная строка таблицы, но когда я пытаюсь сделать так, чтобы пользователь получал строку редактирования, когда он нажимает на редактирование, форма перестает отправлять запросы, когда нажав на кнопку «Отправить».
Когда я открываю инструмент сетевого Chrome, он показывает, что при нажатии на кнопку отправки запрос не отправляется.
Это лезвие компонента

<div x-data="{ open: false }">
    <button @click="open = true" class="bg-gray-900 hover:bg-gray-700 text-white font-bold mb-2 py-2 px-4 rounded">
        Add product
    </button>
    <table class="min-w-full table-fixed text-center">
        <!-- This is the table header -->
        <thead class="justify-between">
            <tr class="bg-gray-900">
                <th class="py-2  ">
                    <span class="text-white"></span>
                </th>
                <th class="py-2">
                    <span class="text-white">Name</span>
                </th>
                <th class="py-2 ">
                    <span class="text-white">Quantity</span>
                </th>
                <th class="py-2">
                    <span class="text-white">Price</span>
                </th>
                <th class="py-2 ">
                    <span class="text-white">Fav</span>
                </th>
                <th class=" py-2">
                    <span class="text-white">Action</span>
                </th>
            </tr>
        </thead>
        <tbody class="bg-gray-200">
            <!-- this is the ADD form that pops up when you click add product -->
            <form autocomplete="off" wire:submit.prevent="formSubmit" action="" method="post">
                @csrf
                <div>
                    <tr class="bg-white border-4 border-gray-200 hover:bg-gray-100 " x-show.transition.duration.500="open" @click.away="open = !open">
                        <td class="px-5 py-2 flex flex-row items-center">
                            <img class="h-8 w-8 rounded-full object-cover " src="https://randomuser.me/api/portraits/men/30.jpg" alt="" />
                        </td>
                        <td>
                            <input type="text" autocomplete="off" wire:model.defer='name' name="name" class="rounded h-6 w-40 border border-gray-900 focus:ring-1 focus:ring-gray-900 ">
                        </td>
                        <td class=" py-2">
                            <input type="number" autocomplete="off" wire:model.defer='quantity' name="quantity" class="rounded h-6 w-16 border border-gray-900 focus:ring-1 focus:ring-gray-900 ">
                        </td>
                        <td class=" py-2">
                            <input type="number" autocomplete="off" wire:model.defer='price' name="price" class="rounded h-6 w-16 border border-gray-900 focus:ring-1 focus:ring-gray-900 ">
                        </td>
                        <td class=" py-2">
                            <input type="checkbox" class=" h-5 w-5 text-red-300 checked:outline-none " checked>
                        </td>
                        <td class=" content-center">
                            <button @click.debounce.500="open = !open" class="w-20 min-w-20 content-center bg-green-600 hover:bg-green-700 text-white font-bold px-4 rounded">
                                <div wire:loading.remove wire:target="formsubmit">
                                    save
                                </div>
                                <div wire:loading wire:target="formsubmit">
                                    <div class="animate-spin w-3  h-3 max-w-3 max-w-3 p-0 m-0  border-t-2 border-l-2 border-r-2  border-white rounded-full loader"></div>
                            </button>
                        </td>
                    </tr>
                </div>
            </form>
            @foreach ($products as $product)
                @if ($product->id == $editedRow)
                    <!-- this is the edit form -->
                    <form wire:submit.prevent="editSubmit" method="POST">
                        <tr class="bg-white border-4 border-gray-200 hover:bg-gray-100" @click.away="$wire.editedRow = null">
                            <td class="px-5 py-2 flex flex-row items-center">
                                <img class="h-8 w-8 rounded-full object-cover " src="https://randomuser.me/api/portraits/men/30.jpg" alt="" />
                            </td>
                            <td class=" py-2">
                                <input value="{{$editname}}" wire:model="editname" type="text" class="rounded h-6 w-36 border border-gray-900 focus:ring-1 focus:ring-gray-900 ">
                            </td>
                            <td class=" py-2">
                                <input value="{{$editquantity}}" wire:model="editquantity" type="text" class="rounded h-6 w-16 border border-gray-900 focus:ring-1 focus:ring-gray-900 ">
                            </td>
                            <td class=" py-2">
                                <input value="{{$editprice}}" wire:model="editprice" type="text" class="rounded h-6 w-16 border border-gray-900 focus:ring-1 focus:ring-gray-900 ">
                            </td>
                            <td class=" py-2"></td>
                            <td>
                                <button type="submit" class="w-20 min-w-20 content-center bg-green-600 hover:bg-green-700 text-white font-bold px-4 rounded">save</button>
                            </td>
                        </form>
                    @else
                        <!-- and finally this is the content of table  -->
                        <tr class="bg-white border-4 border-gray-200 hover:bg-gray-100">
                            <td class="px-5 py-2 flex flex-row items-center">
                                <img class="h-8 w-8 rounded-full object-cover " src="https://randomuser.me/api/portraits/men/30.jpg" alt="" />
                            </td>
                            <td>
                                <span class="text-center ml-2 font-semibold">{{$product->name}}</span>
                            </td>
                            <td class="px-16 py-2">
                                <span>{{$product->quantity}}</span>
                            </td>
                            <td class="px-16 py-2">
                                <span>{{$product->price}}</span>
                            </td>
                            <td class=" py-2">
                                <button wire:click="changeHeart('{{$product->id}}')" class="h-9 w-9 min-h-8 min-w-8 content-center rounded-md border border-transparent text focus:outline-none {{ $product->favourite ? 'bg-gray-300 hover:bg-gray-400' : 'bg-red-300 hover:bg-red-400' }}">
                                    <svg wire:loading.remove wire:target="changeHeart('{{$product->id}}')" xmlns="https://www.w3.org/2000/svg" class="m-auto text-center content-center h-5 w-5 {{ $product->favourite ? 'text-black' : 'text-white' }} " fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                                    </svg>
                                    <div wire:loading wire:target="changeHeart('{{$product->id}}')" class="animate-spin w-5 align-middle h-5 max-h-5 max-w-5   border-t-2 border-l-2 border-r-2 {{ $product->favourite ? ' border-black ' : ' border-white' }} rounded-full loader"></div>
                                </button>
                            </td>
                            <td class="px-16 py-2">
                                <!-- when you click on this you set the editedRow variable to product id  -->
                                <span class="text-blue-500 inline-block mr-1 cursor-pointer">
                                    <svg xmlns="https://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" wire:click='editRow({{$product->id}})'>
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                    </svg>
                                </span>
                                <span class="text-red-500 inline-block ml-1 cursor-pointer">
                                    <svg xmlns="https://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                    </svg>
                                </span>
                            </td>
                        </tr>
                    @endif
                @endforeach
            </div>
        <br>

И это его контролер:

<?php
namespace App\Http\Livewire;

use App\Models\Product;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class ProductsTable extends Component {
public $name;
public $quantity;
public $price;
public $editname;
public $editquantity;
public $editprice;
public $editedRow = null;

public function formSubmit() {
    $product = new Product;
    $product->name = $this->name;
    $product->quantity = $this->quantity;
    $product->price = $this->price;
    $product->save();
    $this->empty();
}
public function empty() {
    $this->name = '';
    $this->quantity = '';
    $this->price = '';
}

public function editRow($id) {
    $product = Product::findorfail($id);
    $this->editedRow = $id;
    $this->editname = $product->name;
    $this->editquantity = $product->quantity;
    $this->editprice = $product->price;
}
public function editSubmit($id) {
    $product = Product::findorfail($id);
    $product->name = $this->name;
    $product->quantity = $this->quantity;
    $product->price = $this->price;
    $product->save();
    $this->empty();
}
public function render() {
    return view('livewire.products-table', ["products" => DB::table('products')->orderBy('name', 'desc')->paginate(9),]);
}

}

И, как вы можете видеть, когда я нажимаю на кнопку «Отправить», запрос не отправляется: https://imgur.com/oZZimsh
если вам нужна дополнительная информация, спрашивайте, я буду регулярно проверять этот пост
Спасибо за ваше время. РЕДАКТИРОВАТЬ: я решил это, что я сделал, так это то, что я отказался от формы и просто связал ввод с переменными в контроллере компонента с помощью wire: model, хотя я не знаю, насколько это безопасно, поскольку я не использовал csrf.

См. также:  Symfony 4 Doctrine не может подключиться к Docker MySQL
Понравилась статья? Поделиться с друзьями:
IT Шеф
Комментарии: 1
  1. Saber Mrabt

    вы забыли @csrf в форме редактирования.

    и зайдите также в Модель продукта, убедитесь, что поля, которые вы пытаетесь заполнить, являются заполняемыми, это не мешает вам создавать, но позволяет редактировать!

    спасибо, что напомнили мне об этом, так что я действительно заставил его работать, просто не используя ‹form›, хотя я не знаю, насколько это безопасно, потому что я не использовал @csrf, надеюсь, вы можете просветить об этом, я ‘ Я собираюсь отредактировать свое решение, если у кого-то возникнет эта проблема person Saber Mrabt; 28.05.2021

    да, я делаю то же самое, я не использую форму, на самом деле она вам не нужна в livewire, так как вы подключаете свои поля, это всегда синхронно! но вам абсолютно необходимо выполнить проверку, даже если вы не используете форму. я не вижу проверки в вашем коде! в конце вы используете empty (), что хорошо. у вас есть два способа выполнить проверку в livewire laravel-livewire.com/docs/2 .x / input-validation person Saber Mrabt; 28.05.2021

Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: