Skip to content

Instantly share code, notes, and snippets.

@Mykola-Veryha
Last active August 29, 2022 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mykola-Veryha/5efdfaffced08a2a2fbbc0aaf456c928 to your computer and use it in GitHub Desktop.
Save Mykola-Veryha/5efdfaffced08a2a2fbbc0aaf456c928 to your computer and use it in GitHub Desktop.
Copy form values
const getFormValuesObject = (selector) => {
const form = document.querySelector(selector);
const formData = new FormData(form);
const formValues = {};
for (const [name, value] of formData.entries()) {
formValues[name] = value;
}
return formValues;
};
const setFormValues = (selector, formValues) => {
const form = document.querySelector(selector);
let editorInstanceName = "";
for (const [name, value] of Object.entries(formValues)) {
editorInstanceName = "edit-" + name.replace(/[\][_]+/g, "-").replace(/-+$/, "");
if (typeof CKEDITOR.instances[editorInstanceName] !== "undefined") {
CKEDITOR.instances[editorInstanceName].setData(value);
}
// Do not edit edit "form_token", "form_id".
if (!name.startsWith("form_")) {
form.elements[name].value = value;
}
}
};
// Example how to copy form values from first form to second one.
// On a browser tab with the first form copy the formValues object from browser console.
const formValues = getFormValuesObject("#formId");
console.log(formValues);
// On a browser tab with the second form.
const formValues = "Put there your copied object";
setFormValues("#formId", formValues);
@Mykola-Veryha
Copy link
Author

const getFormValuesObject = (selector) => {
  const form = document.querySelector(selector);
  const formData = new FormData(form);
  const formValues = {};
  for (const [name, value] of formData.entries()) {
    formValues[name] = value;
  }

  return formValues;
};

// Example how to copy form values from first form to second one.
// On a browser tab with the first form copy the formValues object from browser console.
const formValues = getFormValuesObject("form");
console.log(formValues);

@Mykola-Veryha
Copy link
Author

Mykola-Veryha commented Aug 29, 2022

const setFormValues = (selector, formValues) => {
  const form = document.querySelector(selector);
  let editorInstanceName = "";
  for (const [name, value] of Object.entries(formValues)) {
    editorInstanceName = "edit-" + name.replace(/[\][_]+/g, "-").replace(/-+$/, "");
    if (typeof CKEDITOR.instances[editorInstanceName] !== "undefined") {
      CKEDITOR.instances[editorInstanceName].setData(value);
    }
    // Do not edit edit "form_token", "form_id".
    if (!name.startsWith("form_")) {
      form.elements[name].value = value;
    }
  }
};

// On a browser tab with the second form.
const formValues = "Put there your copied object";
setFormValues("form", formValues);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment