User:L235/formFiller.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | Documentation for this user script can be added at User:L235/formFiller. |
/* Configurable BlankPage Form User‑script
-------------------------------------------------
This script reads its behaviour from a JSON page (for now
[[User:L235/form-config.json]]). Each entry in the JSON defines:
• which page the form appears on (formPage) – OR use the object‑key form
• which questions to render (questions[])
• the page to append to (targetPage)
• the template to insert (+ whether to subst)
JSON can be structured two ways – pick whichever you like:
1. OBJECT keyed by the form page title (simplest):
{
"Special:BlankPage/form": {
"targetPage": "User:L235/sandbox2",
"template": { "name": "User:L235/TestTemplate", "subst": true },
"questions": [ ... ],
"editSummary": "Append answers via BlankPage/form"
},
"Special:BlankPage/animals": {
"targetPage": "User:L235/animals",
"template": { "name": "User:L235/AnimalTemplate", "subst": false },
"questions": [
{ "label": "Question A:", "name": "q1", "type": "text", "required": false, "templateParam": "1" },
{ "label": "Question B:", "name": "q2", "type": "textarea", "required": true, "templateParam": "2" },
{ "label": "Question C:", "name": "q3", "type": "dropdown", "required": false, "options": ["i) apples", "ii) bananas"], "templateParam": "3" },
{ "label": "Question D:", "name": "q4", "type": "checkbox", "required": false, "options": ["cats", "dogs"], "templateParam": "4" },
{ "label": "Question E:", "name": "q5", "type": "radio", "required": true, "options": ["noun", "verb"], "templateParam": "5" },
{ "label": "Section title:", "name": "q6", "type": "text", "required": true, "templateParam": "6" }
]
}
}
2. ARRAY of objects:
[
{
"formPage": "Special:BlankPage/form",
"targetPage": "User:L235/sandbox2",
"template": { "name": "User:L235/TestTemplate", "subst": true },
"questions": [ ... ]
},
{
"formPage": "Special:BlankPage/animals",
"targetPage": "User:L235/animals",
"template": { "name": "User:L235/AnimalTemplate", "subst": true },
"questions": [
{ "label": "Question A:", "name": "q1", "type": "text", "required": false, "templateParam": "1" },
{ "label": "Question B:", "name": "q2", "type": "textarea", "required": true, "templateParam": "2" },
{ "label": "Question C:", "name": "q3", "type": "dropdown", "required": false, "options": ["i) apples", "ii) bananas"], "templateParam": "3" },
{ "label": "Question D:", "name": "q4", "type": "checkbox", "required": false, "options": ["cats", "dogs"], "templateParam": "4" },
{ "label": "Question E:", "name": "q5", "type": "radio", "required": true, "options": ["noun", "verb"], "templateParam": "5" },
{ "label": "Section title:", "name": "q6", "type": "text", "required": true, "templateParam": "6" }
]
}
]
The **questions** array is the same as before; see the first script for field
options. Required fields must set "required": true.
-------------------------------------------------
Save this file as User:<you>/blankpage‑multi‑form.js and import it from your
common.js. Make sure your JSON lives at the path in CONFIG_PAGE below.
*/
/* global mw, $ */
(function () {
var CONFIG_PAGE = 'User:L235/form-config.json';
mw.loader.using(['mediawiki.api', 'oojs-ui']).then(function () {
var api = new mw.Api();
/* ---------- 1. Load JSON config ------------------------------ */
api.get({
action: 'query',
prop: 'revisions',
titles: CONFIG_PAGE,
rvprop: 'content',
formatversion: 2
}).then(function (data) {
var pages = data.query.pages;
if (!pages.length || !pages[0].revisions) {
console.error('[MultiForm] Config page missing or empty');
return;
}
var raw = pages[0].revisions[0].content;
var cfg;
try {
cfg = JSON.parse(raw);
} catch (e) {
console.error('[MultiForm] JSON parse error:', e);
return;
}
var current = mw.config.get('wgPageName').replace(/_/g, ' ');
var formCfg = findMatchingForm(cfg, current);
if (!formCfg) {
return; // not a configured form page – exit silently
}
buildForm(formCfg);
}).fail(function (err) {
console.error('[MultiForm] API error:', err);
});
function findMatchingForm(cfg, pageTitle) {
// OBJECT form – key is the form page
if (!Array.isArray(cfg)) {
if (cfg[pageTitle]) {
return cfg[pageTitle];
}
// maybe keys are something else; scan values for .formPage
for (var key in cfg) {
if (cfg.hasOwnProperty(key) && cfg[key].formPage === pageTitle) {
return cfg[key];
}
}
} else {
// ARRAY style
for (var i = 0; i < cfg.length; i++) {
if (cfg[i].formPage === pageTitle) {
return cfg[i];
}
}
}
return null;
}
/* ---------- 2. Render form ----------------------------------- */
function buildForm(config) {
var $content = $('#mw-content-text').empty();
$content.append($('<h2>').text(config.title || 'Submit your answers'));
var $form = $('<form>').appendTo($content);
config.questions.forEach(function (q) {
renderQuestion($form, q);
$form.append('<br><br>');
});
var $submit = $('<input>').attr({ type: 'submit', value: 'Submit' });
$form.append($submit);
$form.on('submit', function (e) {
e.preventDefault();
handleSubmit($form, config, $submit);
});
}
function renderQuestion($form, q) {
var $label = $('<label>').text(q.label + (q.required ? ' (required): ' : ': '));
var $field;
switch (q.type) {
case 'text':
$field = $('<input>').attr({ type: 'text', name: q.name, size: 40 });
break;
case 'textarea':
$field = $('<textarea>').attr({ name: q.name, rows: 4, cols: 60 });
break;
case 'dropdown':
$field = $('<select>').attr('name', q.name);
q.options.forEach(function (opt) {
$field.append($('<option>').val(opt).text(opt));
});
break;
case 'checkbox':
$field = $('<span>');
q.options.forEach(function (opt) {
var $l = $('<label>');
$l.append($('<input>').attr({ type: 'checkbox', name: q.name, value: opt }), ' ', opt, '\u00A0');
$field.append($l);
});
break;
case 'radio':
$field = $('<span>');
q.options.forEach(function (opt, idx) {
var $l = $('<label>');
$l.append($('<input>').attr({
type: 'radio', name: q.name, value: opt,
required: q.required && idx === 0
}), ' ', opt, '\u00A0');
$field.append($l);
});
break;
default:
console.warn('[MultiForm] Unsupported field type:', q.type);
return;
}
if (q.required && q.type !== 'radio') {
$field.attr('required', true);
}
$form.append($label.append($field));
}
/* ---------- 3. Submission ------------------------------------ */
function getValue($form, q) {
switch (q.type) {
case 'checkbox':
return $form.find('[name=' + q.name + ']:checked').map(function () {
return this.value;
}).get().join(', ');
case 'radio':
return $form.find('[name=' + q.name + ']:checked').val() || '';
default:
return $form.find('[name=' + q.name + ']').val().trim();
}
}
function handleSubmit($form, config, $submit) {
var missing = config.questions.filter(function (q) {
return q.required && !getValue($form, q);
});
if (missing.length) {
alert('Please fill required fields: ' + missing.map(function (q) {
return q.label.replace(/:\s*$/, '');
}).join(', '));
return;
}
var params = config.questions.map(function (q) {
return '|' + q.templateParam + '=' + getValue($form, q);
}).join('');
var tplName = config.template.name || config.template;
if (config.template.subst) tplName = 'subst:' + tplName;
var wikitext = '\n{{' + tplName + params + '}}\n';
$submit.prop('disabled', true).val('Submitting…');
api.postWithToken('csrf', {
action: 'edit',
title: config.targetPage,
appendtext: wikitext,
summary: config.editSummary || 'Append answers via multi‑form script'
}).done(function () {
mw.notify('Saved!', { type: 'success' });
$form[0].reset();
}).fail(function (err) {
console.error('[MultiForm] Edit error:', err);
mw.notify('Error: ' + err, { type: 'error', autoHide: false });
}).always(function () {
$submit.prop('disabled', false).val('Submit');
});
}
});
})();