skip to Main Content

Uploading the images has no problem but when deleting the uploaded images, it triggers the store button instead. I am wondering why is this happening?

Controller code:

public function store(Request $request)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'description' => 'required|max:150',
            'category_id' => 'required',
            'type_id' => 'required',
            'price' => 'required|numeric|min:0|not_in:0',
            'start_date' => 'required',
            'end_date' => 'required',
            'is_active' => 'required',
            'images.*' => 'image|max:2048', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 2MB
        ]);

        $product = DB::table('products')
            ->insertGetId([
                'name' => $data['name'],
                'description' => $data['description'],
                'type_id' => $data['type_id'],
                'category_id' => $data['category_id'],
                'price' => $data['price'],
                'start_date' => $data['start_date'],
                'end_date' => $data['end_date'],
                'is_password' => $request['is_password'],
                'is_stamping' => $request['is_stamping'],
                'created_at' => now(),
            ]);

        // handle image uploads
        if ($request->hasFile('images')) {
            $i = 1;
            foreach ($request->file('images') as $image) {
                $name = $request['name'] . '-' . $i;
                $now = new DateTime();
                $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $i . '.' . $image->getClientOriginalExtension();
                //$fileName = Str::slug($request['name']) . '-' . time() . '.' . $image->getClientOriginalExtension();
                $path = $image->storeAs('public/Product/Images', $fileName);
                DB::table('product_images')->insert([
                    'product_id' => $product,
                    'name' => $name,
                    'file_path' => Storage::url($path),
                    'created_at' => now(),
                ]);
                $i++;
            }
        }
}
        return Redirect::route('produk.index');
    }

public function update(Request $request, $id)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'description' => 'required|max:150',
            'category_id' => 'required',
            'type_id' => 'required',
            'price' => 'required|numeric|min:0|not_in:0',
            'start_date' => 'required',
            'end_date' => 'required',
            'is_active' => 'required',
            'images.*' => 'image|max:2048', // max file size: 2MB
            'documents.*' => 'file|max:2048', // max file size: 2MB
        ]);

        DB::table('products')
            ->where('id', $id)
            ->update([
                'name' => $data['name'],
                'description' => $data['description'],
                'type_id' => $data['type_id'],
                'category_id' => $data['category_id'],
                'price' => $data['price'],
                'start_date' => $data['start_date'],
                'end_date' => $data['end_date'],
                'is_active' => $data['is_active'],
                'is_password' => $request['is_password'],
                'is_stamping' => $request['is_stamping'],
                'updated_at' => now(),
            ]);

        // handle image uploads
        if ($request->hasFile('images')) {
            //DB::table('product_images')->where('product_id', $id)->delete();
            //Storage::deleteDirectory('public/Product/Images/' . $id);
            foreach ($request->file('images') as $image) {
                $name = $request['name'] . '-' . $id;
                $now = new DateTime();
                $fileName = Str::slug($request['name']) . '-' . $now->format('dmYHis') . '-' . $id . '.' . $image->getClientOriginalExtension();
                $path = $image->store('public/Product/Images/' . $fileName);
                DB::table('product_images')->insert([
                    'product_id' => $id,
                    'file_path' => Storage::url($path),
                    'created_at' => now(),
                ]);
            }
        }
return Redirect::route('produk.index');
    }

The button that gets triggered,

const formik = useFormik({
        initialValues: {
            name: action === "create" ? "" : `${data.name}`,
            description: action === "create" ? "" : `${data.description}`,
            category_id: action === "create" ? "" : `${data.category_id}`,
            type_id: action === "create" ? "" : `${data.type_id}`,
            price: action === "create" ? "" : `${data.price}`,
            is_active: action === "create" ? "" : `${data.is_active}`,
            start_date: action === "create" ? "" : `${data.start_date}`,
            end_date: action === "create" ? "" : `${data.end_date}`,
            // is_password: action === "create" ? "" : `${data.is_password}`,
            // is_stamping: action === "create" ? "" : `${data.is_stamping}`,
        },
        validationSchema: validationSchema,

        onSubmit: async (values) => {
            try {
                switch (action) {
                    case "create":
                        await post(route("produk.store"));
                        Swal.fire({
                            text: "Maklumat produk berjaya disimpan",
                            icon: "success",
                        });
                        break;
                    case "update":
                        await put(route("produk.update", product.id), data);
                        Swal.fire({
                            text: "Maklumat produk berjaya dikemaskini",
                            icon: "success",
                        });
                        break;
                }
            } catch (error) {
                Swal.fire({
                    icon: "error",
                    title: "Oops...",
                    text: "Something went wrong!",
                });
            }
        },
    });

    return (
        <form method={"post"} onSubmit={formik.handleSubmit}>

                        ....................

Delete button to remove file upload when adding product

{/* Delete button to remove file upload when adding product */}
    const removeFileUpload = (e, index) => {
        const updatedFileUpload = [...fileUpload];
        updatedFileUpload.splice(index, 1);
        setFileUpload(updatedFileUpload);
        setData(name, updatedFileUpload);
    };

Delete button to remove img when editing/updating product

return (
                   ...........
                    
{/* Delete Button when editing/update */}
        <button
           onClick={() => removeFileUpload(index)}
           className="outline-none border-none"
         >
           <FaTimes className="text-red-600" />
        </button>
.....

2

Answers


  1. Chosen as BEST ANSWER

    I found the solution. I have to create a new function when clicking the button as such,

    /* Delete documents button when updating/editing form*/
        const removeFileUpload2 = async (type) => {
            console.log("🚀 ~ removeFileUpload2 ~ type:", type);
            try {
                const fileType = type.file_path.endsWith(".pdf")
                    ? "document"
                    : "image";
                const routeName =
                    fileType === "document"
                        ? "product-documents.destroy"
                        : "product-images.destroy";
                await Inertia.delete(route(routeName, type));
                Swal.fire(
                    "Berjaya!",
                    `Rekod jenis ${fileType} berjaya dipadam.`,
                    "success"
                );
            } catch (error) {
                Swal.fire("Ralat!", error.response.data.message, "error");
            }
        }
    

    And then use it on the button,

        <span
             onClick={() => removeFileUpload2(file)}
             className="outline-none border-none cursor-pointer"
        >
             <FaTimes className="text-red-600" />
        </span>
    

  2. The most probable reason could be that the button is within the form element, which triggers the form submit. You should add

    event.preventDefault();
    

    to the event listener of the delete handler , so it doesn’t bubbles the event to top elements or you could move the delete button out side the form tag

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search