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. |
/* **JSON schema (examples)**
Object‑key style:
{
"Special:BlankPage/form": {
"title": "Demo survey",
"instructions": "<p>Please fill the survey. Fields marked required.</p>",
"targetPage": "User:L235/sandbox2",
"template": { "name": "User:L235/TestTemplate", "subst": true },
"questions": [
{ "label": "Question A", "name": "q1", "type": "text", "templateParam": "1", "default": "foo" },
{ "label": "Question B", "name": "q2", "type": "textarea", "required": true, "templateParam": "2" },
{ "type": "heading", "text": "Choices" },
{ "label": "Question C", "name": "q3", "type": "dropdown", "options": ["apples", "bananas"], "templateParam": "3", "default": "bananas" },
{ "label": "Question D", "name": "q4", "type": "checkbox", "options": ["cats", "dogs"], "templateParam": "4", "default": ["cats"] },
{ "label": "Question E", "name": "q5", "type": "radio", "options": ["noun", "verb"], "required": true, "templateParam": "5", "default": "verb" },
{ "label": "Section title", "name": "q6", "type": "text", "required": true, "templateParam": "6" },
{ "type": "static", "html": "<em>Thanks for participating!</em>" }
]
}
}
*/
/* 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 page = data.query.pages[0];
if (!page.revisions) {
console.error('[MultiForm] Config page missing or empty');
return;
}
var raw = page.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 = matchForm(cfg, current);
if (!formCfg) return;
renderForm(formCfg);
}).fail(function (err) {
console.error('[MultiForm] API error:', err);
});
/* ---------- helper: find config for this page ---------------- */
function matchForm(cfg, page) {
if (Array.isArray(cfg)) {
return cfg.find(function (f) { return f.formPage === page; });
}
if (cfg[page]) return cfg[page];
return Object.values(cfg).find(function (f) { return f.formPage === page; });
}
/* ---------- 2. Render form ----------------------------------- */
function renderForm(cfg) {
var $content = $('#mw-content-text').empty();
if (cfg.title) $content.append($('<h2>').text(cfg.title));
if (cfg.instructions) $content.append($(cfg.instructions));
var $form = $('<form>').appendTo($content);
(cfg.questions || []).forEach(function (q) {
insertItem($form, q);
});
$form.append('<br>');
var $submit = $('<input>').attr({ type: 'submit', value: 'Submit' });
$form.append($submit);
$form.on('submit', function (e) {
e.preventDefault();
submit($form, cfg, $submit);
});
}
/* ---------- insert question or static block ------------------ */
function insertItem($form, q) {
switch (q.type) {
case 'heading':
$form.append($('<h3>').text(q.text));
return;
case 'static':
case 'html':
$form.append($(q.html || '<p>' + (q.text || '') + '</p>'));
return;
}
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, value: q.default || '' });
break;
case 'textarea':
$field = $('<textarea>').attr({ name: q.name, rows: 4, cols: 60 }).text(q.default || '');
break;
case 'dropdown':
$field = $('<select>').attr('name', q.name);
(q.options || []).forEach(function (opt) {
var $o = $('<option>').val(opt).text(opt);
if (opt === q.default) $o.attr('selected', true);
$field.append($o);
});
break;
case 'checkbox':
$field = $('<span>');
var defaults = Array.isArray(q.default) ? q.default : (q.default ? [q.default] : []);
(q.options || []).forEach(function (opt) {
var $l = $('<label>');
var $cb = $('<input>').attr({ type: 'checkbox', name: q.name, value: opt });
if (defaults.includes(opt)) $cb.prop('checked', true);
$l.append($cb, ' ', opt, '\u00A0');
$field.append($l);
});
break;
case 'radio':
$field = $('<span>');
(q.options || []).forEach(function (opt, idx) {
var $l = $('<label>');
var $rb = $('<input>').attr({ type: 'radio', name: q.name, value: opt });
if (q.required && idx === 0) $rb.attr('required', true);
if (opt === q.default) $rb.prop('checked', true);
$l.append($rb, ' ', opt, '\u00A0');
$field.append($l);
});
break;
default:
console.warn('[MultiForm] Unsupported field type:', q.type);
return;
}
if (q.required && !['radio', 'checkbox'].includes(q.type)) $field.attr('required', true);
$form.append($label.append($field)).append('<br><br>');
}
/* ---------- 3. Submission ------------------------------------ */
function valueOf($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 submit($form, cfg, $submit) {
// validate required questions (skip static)
var missing = (cfg.questions || []).filter(function (q) {
return q.required && q.name && !valueOf($form, q);
});
if (missing.length) {
alert('Please fill required fields: ' + missing.map(function (q) { return q.label; }).join(', '));
return;
}
var params = (cfg.questions || []).filter(function (q) { return q.templateParam; }).map(function (q) {
return '|' + q.templateParam + '=' + valueOf($form, q);
}).join('');
var tpl = cfg.template.name || cfg.template;
if (cfg.template.subst) tpl = 'subst:' + tpl;
var wikitext = '\n{{' + tpl + params + '}}\n';
$submit.prop('disabled', true).val('Submitting…');
api.postWithToken('csrf', {
action: 'edit',
title: cfg.targetPage,
appendtext: wikitext,
summary: cfg.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');
});
}
});
})();