I connected a form_with with my stimulus controller, then added the form itself as a target and added an action to point to my stimulus controller’s submit function. When I then get the form and try to form.submit() I get this error that reads:
Can’t verify CSRF token authenticity.
My form_with html tag:
<%= form_with(model: @example, data: { controller: "nested-form", nested_form_target: "form", action: "submit->nested-form#submit" }, local: false) do |form| %>
My static targets:
static targets = [
"skillsContainer",
"communitiesContainer",
"template",
"form",
];
My submit function:
submit(event) {
event.preventDefault();
const form = this.formTarget;
form.submit();
}
I tried adding a hidden field in the form with the token:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
Also tried to add the action directly to the form.submit tag
<%= form.submit "Save Sprint Goal", class: "btn btn-primary", style: "border-radius: 10px;", action: "click->nested-form#submit"%>
I have the CSRF metatag in my layout and I’m succesfully sending requests in other stimulus controllers using the CSRF.
Daniel Gaspar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.