diff --git a/symfony/stimulus-bundle/2.24/assets/controllers/csrf_protection_controller.js b/symfony/stimulus-bundle/2.24/assets/controllers/csrf_protection_controller.js index 511fffa5c..bcf6b14c8 100644 --- a/symfony/stimulus-bundle/2.24/assets/controllers/csrf_protection_controller.js +++ b/symfony/stimulus-bundle/2.24/assets/controllers/csrf_protection_controller.js @@ -23,7 +23,7 @@ document.addEventListener('turbo:submit-end', function (event) { }); export function generateCsrfToken (formElement) { - const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]'); + const csrfField = getCsrfField(formElement); if (!csrfField) { return; @@ -46,7 +46,7 @@ export function generateCsrfToken (formElement) { export function generateCsrfHeaders (formElement) { const headers = {}; - const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]'); + const csrfField = getCsrfField(formElement); if (!csrfField) { return headers; @@ -62,7 +62,7 @@ export function generateCsrfHeaders (formElement) { } export function removeCsrfToken (formElement) { - const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]'); + const csrfField = getCsrfField(formElement); if (!csrfField) { return; @@ -77,5 +77,17 @@ export function removeCsrfToken (formElement) { } } +function getCsrfField (formElement) +{ + // Input element is placed inside the form + const qSel = 'input[data-controller="csrf-protection"], input[name="_csrf_token"]'; + const csrfField = formElement.querySelector(qSel); + if (csrfField) {return csrfField;} + + // Input element is placed outside the form + return Array.from(document.querySelectorAll(qSel)) + .find((field) => field.form === formElement) || null; +} + /* stimulusFetch: 'lazy' */ export default 'csrf-protection-controller';