Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/addons/attract/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,12 @@ class Form {
event.preventDefault();

const action = this.form.getAttribute("action");
const method = (this.form.getAttribute("method") || "post").toUpperCase();

const override = this.form.querySelector('input[name="_method"]');
const method = (
override?.value ||
this.form.getAttribute("method") ||
"post"
).toUpperCase();
if (!action) return;

const body = this.#data();
Expand Down Expand Up @@ -63,6 +67,8 @@ class Form {
const body = {};

for (const [key, value] of formData.entries()) {
if (key === "_method") continue;

body[key] = value;
}

Expand Down
36 changes: 36 additions & 0 deletions tests/addons/attract.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,42 @@ describe("attract addon", () => {
expect(fetchMock).toHaveBeenCalled();
});

test("honors a _method override field (PATCH/PUT/DELETE tunneling)", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
headers: new Headers({ "Content-Type": "application/json" }),
json: () => Promise.resolve({})
});
globalThis.fetch = fetchMock;

document.body.innerHTML = `
<form @attract action="/messages/1" method="post">
<input type="hidden" name="_method" value="patch" />
<input name="body" value="updated" />
<button>Submit</button>
</form>
`;

attractive.activate({
addActions: allBuiltinActions,
addGates: builtinGates,
addTriggers: builtinTriggers,
extendWith: [attract]
});

const form = document.querySelector("form");
form.dispatchEvent(
new Event("submit", { bubbles: true, cancelable: true })
);
await vi.runAllTimersAsync();

expect(fetchMock).toHaveBeenCalled();
const [url, options] = fetchMock.mock.calls[0];
expect(url).toBe("/messages/1");
expect(options.method).toBe("PATCH");
expect(JSON.parse(options.body)).not.toHaveProperty("_method");
});

test("processes actions from response", async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
Expand Down
Loading