Extension:Simple Forms
From MediaWiki.org
|
Simple Forms Release status: beta |
|
|---|---|
| Implementation | Parser function, Page action, Ajax |
| Description | A set of simple mechanisms for making and processing forms |
| Author(s) | User:Nad |
| Version | 0.4.9 (2008-04-24) |
| MediaWiki | 1.6.0 - 1.11.0 |
| Download | Extension:SimpleForms.php |
We've needed forms for quite a number of things in our Organic Design wiki such as for creating or editing articles which are based on templates or for making DynamicPageList queries. Instead of making specific code for each form instance, we decided to create a generic set of simple mechanisms which could be re-used to make the creation of all forms and their processing much simpler.
The SimpleForms extension extends the functionality of MediaWiki in two main ways:
- parser-functions: by adding extra parser functions (accessed using curly-brace syntax in an article's wikitext) which are used for constructing forms and accessing the posted data.
- index.php parameters: by adding additional parameters to index.php articles can be updated and created directly from parameters passed in links or posted data.
Contents |
[edit] Installation & configuration
This extension is a single script which is included at the end of your LocalSettings.php file as usual. Download the current version from OrganicDesign:Extension:SimpleForms.php and save it in your extensions directory or in a subdirectory to suit the organisation of your extensions.
There are also a number of global configuration variables for enabling, disabling and setting up the various features of the SimpleForms extension. These should be set in your LocalSettings file after the include of the SimpleForms.php script. Here is a description of the valid variables.
| Variable | Default value | Meaning |
|---|---|---|
| $wgSimpleFormsFormMagic | form | the parser-function name for form containers |
| $wgSimpleFormsInputMagic | input | the parser-function name for making form-inputs |
| $wgSimpleFormsRequestMagic | request | the parser-function name for accessing the GET/POST variables |
| $wgSimpleFormsRequestPrefix | empty | prefix that restricts #request and GET/POST variable names to their own namespace, set to "" to disable |
| $wgSimpleFormsAllowCreate | true | whether or not creating articles from query-string is allowed |
| $wgSimpleFormsAllowEdit | true | whether or not editing articles from query-string is allowed |
| $wgSimpleFormsAllowRemoteAddr | Server-IP, 127.0.0.1 | IP addresses in this list are allowed to update or create articles without requiring login. This makes it easy for programs on the server to update wiki content without needing to parse and post a login form. |
| $wgSimpleFormsServerUser | empty | Set this to a username to show in the changes for edits by the server rather than showing the IP address |
[edit] Ajax
The Simple Forms extension can use Ajax technology to allow forms or links to work asyncronously (i.e. not involving a page reload). The content in the server's response can be directed to replace a particular portion of the page identified by it's id attribute. Simple Forms used to use the MooTools JavaScript framework for its Ajax functionality, but now it only requires the inbuilt MediaWiki Ajax functions. These must be enabled by setting $wgUseAjax to true in your LocalSettings.php file before the inclusion of Simple Forms as in the following example.
$wgUseAjax = true;
include("$IP/extensions/Simple Forms/Simple Forms.php");
- Note: Simple Forms ajax functionality requires a version of skins/common/ajax.js from at least MediaWiki 1.8.x.
- See also: related note #Using MediaWiki Ajax instead of MooTools below
[edit] Form Syntax & Style
Form syntax is made clearer by using indentation, but it is important to note that whitespace indentation using space characters may lead to undesired results. For this reason, indentation should always be done using tab characters rather than spaces because SimpleForms removes all tabs from the form definition before it gets processed.
Class and id attributes can be added to the #form or #input parser-function syntax, or to surrounding div elements etc to customise form design and layout from your wiki's CSS stylesheet. CSS rules can be added to the MediaWiki:Common.css article rather than editing the CSS file.
- Ajax links have ajax added to their class attribute so they can be given a specific link style
[edit] SimpleForms parser functions
We wanted forms to be created or modified by unprivileged users, so we decided against allowing form articles to use raw HTML and instead added some parser functions, which allow forms to be created, and the posted results captured using normal wikitext notation.
[edit] #form
The first parser function is #form which defines the main form container. Three parameters can be supplied, the first two are method and action, which serve the same purpose as usual, except that method can be the name of a javascript function if it's not GET or POST. The third parameter is target which either has the normal meaning, or if the action refers to a function, then the target property refers to a part of the document the result should be sent to.
The JavaScript functions which the form can execute should return a URL (including an optional query-string component) which will then be asyncronously requested from the server using an xmlhttp object. The returned content will replace the content (innerHTML property) of the document element having the id specified in the form's target property.
There's currently just one JavaScript function which is called live, using this as the action of the form requests the URL usign an asyncrounous xmlhttp-POST request and adds all the form's input values to the request.
[edit] #input
Form inputs are made with the #input parser function, no JavaScript is allowed in the values, except for names of the functions which are registered in the global $wgJavaScriptFunctions array.
Select-lists and textareas can be created using the #input function with type set to select, textarea rather than having them consuming their own magic.
[edit] Input types
In addition to the normal input types list text, image or checkbox, there are the following additional types and properties:
type=select: this is used for dropdown selection lists instead of having a dedicated #select parser function.
type=textarea: this is used for textareas instead of having a dedicated #textarea parser function.
type=submit: this does the same as usual, but can also be combined with method=ajax to make the form submission asyncronous.
type=ajax: the works like a normal input with type=submit which submits the forms except that the submission will occur asyncronously without reloading the page. Add the update parameter set to the id attribute of the element on the page that the results should be rendered in. The Ajax input type also allows a parameter called link which can be set to a URL or article title and causes the input to render as a normal hyperlink instead of as a form button. These link inputs are independent of any form, see OrganicDesign:19 June 2007 for a working example of this type of input.
[edit] #request
This allows values from the query-string (GET) or POSTed data to be included in the article to be used by other parser functions when calculating or rendering their results. For example, an article could be made something like the following example which would list the items in a category if its been specified, or render a form otherwise.
{{#if: {{#request:cat}}
|{{#dpl:category={{#request:cat}}}}
|{{#form:
{{#input:type=select|name=cat|{{#dpl:namespace=Category|format=,\n*%TITLE%,,}}}}
{{#input:type=submit|value=List members}}
}}
}}
- Note1: Indenting is optional, but must use tabs not spaces, because spaces at the start of the line cause <pre> sections
- Note2: This example works, but requires the ParserFunctions and DynamicPageList extensions.
The form which is rendered also exhibits a DPL query which creates a list of all categories for the dropdown select-list. The #input function expects to have a standard wikitext bullet list supplied for its list of options, so the DPL query sets the mode and listseparators parameters appropriately.
[edit] SimpleForms index.php parameters
The SimpleForms extension adds a number of extra parameters to index.php which allows articles to be updated and created directly from HTTP requests without having to process HTML content. Following is an explanation of each of the additional parameters available.
[edit] content
The SimpleForms extension offers the ability to specify wikitext content directly in the posted data or query string using the content parameter. This is useful for adding default content to newly created articles, but the main reason we created it was so that forms could use their JavaScript functions to compose wikitext from the form's inputs and then request the parsed result. This effectively allows forms to execute dynamic, transient queries without having to adjust any article content. It's similar to doing a page-preview, but doesn't use any edit form.
- <nowiki> tag usage in the content parameter
The wikitext in the content parameter can be surrounded by a <nowiki> element so that it's easy to assign wikitext queries to it without them being parsed. These nowiki elements will be automatically stripped by SimpleForms when the form is posted.
- Using content and title together
If the content parameter is used without any title parameter, then it will be parsed and the result returned without any article being accessed at all by MediaWiki. This feature is used by the search example shown below. If there is a title parameter, but the article doesn't exist, then the article will be created from the content (subject to the $wgSimpleFormsAllowCreate variable). And finally if there is both a content and title parameter and the article does already exist, then what happens to the content depends on the caction (content-action) parameter which is described below.
- Notes
- The content query-string item can be used in conjunction with the usual actions, but would usually only be used with action=edit, action=render (or maybe action=raw&templates=expand).
- Currently the content query-item does not work with action=edit
- There is a MediaWiki API under development to allow adjustment of content via the request variables inherently, which this extension will make use of when it is ready.
- Currently friendly URLs in conjunction with the content item (eg. http://www.foo.com/MyArticle?content=SomeWikitext) does not work. So long-form URLs (eg. http://www.foo.com/wiki/index.php?title=MyArticle&content=SomeWikitext) should always be used, but it's advisable to stick with long-form for functional URLs anyway as they're wiki-environment independent.
[edit] caction = replace | append | prepend
The content item can be used with another item called caction (content-action) which defines how the content should be incorporated into an existing article specified by the title parameter.
- replace (default)
- prepend
- append
[edit] regexp
If the regexp parameter can be set to a PERL-compatible regular expression, an attempt will be made to replace the any matching patterns of text in the article with the content parameter. If there are no matching patterns, then the content will be replaced, appended or prepended according to the caction parameter.
[edit] templates = update
This query-string parameter is usually used with action=raw to cause the raw wikitext to have its double-braces (templates, variables and parser-functions) expanded first.
The Simple Forms extension allows the templates parameter to also be used with content. The only applicable value for the templates parameter when used with content is update which causes any templates in the content to update their counterpart in the current content. Any template having no match will be appended. Any having more than one match will cause Simple Forms to try and reduce the matches to a single result by comparing values of the first named parameter. The following table helps to illustrate this:
| Initial article text | Content of templates to merge | Updated article text |
|---|---|---|
{{foo|parameter1|parameter2}}
{{bar|parameter1}}
{{baz|{{hello:world}}}}
|
{{bar|p4|p5|p6}}
|
{{foo|parameter1|parameter2}}
{{bar|p4|p5|p6}}
{{baz|{{hello:world}}}}
|
In this example, the content supplied has an unambihuous match with the bar template definition which gets replaced.
{{foo|parameter1|parameter2}}
{{bar|parameter1}}
{{baz|{{hello:world}}}}
|
{{moo}}
|
{{foo|parameter1|parameter2}}
{{bar|parameter1}}
{{baz|{{hello:world}}}}
{{moo}}
|
In this case the content has been appended because there were no template matches.
{{#contact:name=Joe|phone=1234567}}
{{#contact:name=Jane|phone=587983579}}
{{#contact:name=John|phone=23547101}}
|
{{#contact:name=Jane|address=foo ave}}
|
{{#contact:name=Joe|phone=1234567}}
{{#contact:name=Jane|address=foo ave}}
{{#contact:name=John|phone=23547101}}
|
Here all the templates match by name, so an attempt is made to reduce this ambiguous state by comparing the first parameters, in this case the "name" parameter which matches "Jane". The contact entry for "Jane" gets replaced, the phone number has been removed because it was not supplied in the new content. If none of the first parameters matched, the update would be appended to the article as in the previous example.
{{#contact:name=Joe|phone=1234567}}
{{#contact:name=Jane|phone=587983579}}
{{#contact:name=John|phone=23547101}}
|
{{#contact:name=Jane|address=foo ave}}
{{#contact:name=Jim|phone=11223344}}
|
{{#contact:name=Joe|phone=1234567}}
{{#contact:name=Jane|address=foo ave}}
{{#contact:name=John|phone=23547101}}
{{#contact:name=Jim|phone=11223344}}
|
This example shows content to update containing more than one template definition (both the items from the previous two examples). As can be seen, the result is the same as if the two were processed one at a time, i.e. the first updates the "Jane" entry, and the second appends since there's no unique match.
[edit] summary
If a more specific edit summary is preferred to the default, then it can be supplied in this parameter.
[edit] minor (not done yet)
If any changes are made, they will be marked as minor edits.
[edit] pagename
If the content parameter is used without a title parameter, then the returned page containing the parsed content will, by default, have no title, but if a title for the page is desired it can be set using this parameter. The search-form example below uses this feature to add a "search results" title to the page.
[edit] username
If the client is autoauthenticated as being the server (The requesting IP address is one of those contained in the $wgSimpleFormsAllowRemoteAddr array), then it can be changed to a different name by setting this parameter. This allows the server to forward edits to the wiki from other sources and protocols on behalf of the wiki users.
[edit] returnto
Set this to an article title that should be returned after processing the request, this is useful if the page being updated is very large and doesn't need to be returned.
[edit] action = render
SimpleForms allows the usual MediaWiki render action to also work with special pages. This is very useful as it allows results of special page queries such as Special:DynamicPageList to be used with Ajax requests.
[edit] SimpleForms Usage Examples
[edit] Ajax example
This example renders a form with a dropdown list containing all the categories in the wiki, when one of them is selected and the submit button clicked, an Ajax request is generated which returns a list of all articles in the selected category. This list is then put into the content of a div element below the form. To see the example working, see OrganicDesign:18 June 2007 (also OrganicDesign:19 June 2007 may be of interest as an example of using ajax links). Here's the wikitext source of the example,
{{#form:
{{#input: type = hidden | name = content | value = <nowiki>{{#dpl:category={{#request:cat}}}}</nowiki> }}
{{#input: type = select
| name = cat
| value = {{#request:cat}}
| *Select category {{#dpl: namespace = Category | format = ,\n*%TITLE%,, }}
}}
{{#input: type = ajax | value = List members | update = listcat-result}}
}}
<div id="listcat-result">NO RESULTS TO DISPLAY YET</div>
The second hidden value, content contains the DPL query which produces the list of article in the category. The query uses the #request parser-function to obtain the selected category which was posted in the input named cat. Notice that the wikitext of the DPL query has to be enclosed in a <nowiki> so that the unparsed wikitext query can be assigned to the hidden value. After the form content has been posted, SimpleForms will remove the surrounding <nowiki>'s before the content gets parsed.
The last input, with type=ajax works just like a normal submit button, but will work asyncronously using Ajax. the update parameter is used to direct the content of the server response to the element having id of "listcat-result" which is the div below the form.
[edit] A user login form
This form example replicates the same form inputs as a normal login form and posts them to the Special:Userlogin page.
{{#form:method=post|
{{#input:type=hidden|name=title|value=Special:Userlogin}}
{{#input:type=hidden|name=action|value=submitlogin}}
{{#input:type=hidden|name=type|value=login}}
{{#input:type=hidden|name=returnto|value={{FULLPAGENAMEE}}}}
{{#input:type=hidden|name=wpLoginattempt|value=Log in}}
{{#input:type=text|name=wpName}}
{{#input:type=password|name=wpPassword}}
{{#input:type=submit|value=Login}}
}}
[edit] A PayPal donation form
Here's an example which creates a standard PayPal donation form. Update the values to your own paypal-registered email address, and product name. Notice the nowiki tags which are required to protect the URL's from the wiki-parser.
{{#form:action=https://www.paypal.com/cgi-bin/webscr|method=POST|
{{#input:type=hidden|name=business |value = donations@company.com }}
{{#input:type=hidden|name=item_name|value = Product Name }}
{{#input:type=hidden|name=cmd|value=_xclick}}
{{#input:type=hidden|name=no_shipping|value=0}}
{{#input:type=hidden|name=no_note|value=1}}
{{#input:type=hidden|name=currency_code|value=USD}}
{{#input:type=hidden|name=tax|value=0}}
{{#input:type=hidden|name=bn|value=PP-DonationsBF}}
{{#input:type=image|src=https://www.paypal.com/en_US/i/btn/x-click-but04.gif|name=submit}}
{{#input:type=image|alt=|border=0|src=https://www.paypal.com/en_US/i/scr/pixel.gif|width=1|height=1}}
}}
[edit] A form to categorise the current article
This example show how to make a form allowing the user to categorise the current page. When an item is selected from the dropdown list, the form's content and regexp parameters are updated. The regexp parameter is used to prevent more than one occurence of the same category link. If there are no matching category links, then a new one will be appended. To see this example working, go to OrganicDesign:SimpleForms categorisation example.
{{#form:
{{#input:type=hidden|name=title|value={{FULLPAGENAMEE}}}}
{{#input:type=hidden|name=summary|value=Article category updated from form}}
{{#input:type=hidden|name=caction|value=append}}
{{#input:type=hidden|name=regexp|id=setcat-regexp}}
{{#input:type=hidden|name=content|id=setcat-content}}
{{#input: type = select
| *Select category{{#dpl: namespace = Category | format = ,\n*%TITLE%,, }}
| onChange =
document.getElementById('setcat-regexp').setAttribute('value','\\[\\[Category:'+this.value+'.*?\\]\\]');
document.getElementById('setcat-content').setAttribute('value','['+'[Category:'+this.value+']'+']');
}}
{{#input:type=submit|value=Categorise!}}
}}
[edit] Blog Example
This example allows the user to post comments to an article's talk page using a dynamic Ajax form, see this example in action at OrganicDesign:Blog example. Comments are posted to the article's talk page dynamically. The talk page is transcluded and a form allows users to enter a heading, their name and a comment which is then dynamically appended to the talk page and the transcluded content updated via an Ajax request. The submit button looks rather complicated, this is because the content being appended to the talk page needs to be composed by the Javascript from the title, name and body inputs.
== Comments ==
<div id='wgBlogComments'>{{Talk:{{PAGENAMEE}}}}</div>
{{#form:
{{#input:type=hidden|name=content|id=blogContent}}
{{#input:type=hidden|name=title|value=Talk:{{PAGENAMEE}}}}
{{#input:type=hidden|name=summary|id=blogSummary}}
{{#input:type=hidden|name=caction|value=append}}
Heading: {{#input:type=text|id=blogTitle}}
Your name: {{#input:type=text|id=blogName}}
Comment: {{#input:type=textarea|rows=2|id=blogBody}}
{{#input:type=ajax|value=Post comment|update=wgBlogComments|onClick=
var summary='comment posted by '+document.getElementById('blogName').value;
document.getElementById('blogContent').setAttribute('value',
'\n==='+document.getElementById('blogTitle').value+'===\n'+document.getElementById('blogBody').value+'\n:<i>'+summary+'</i>\n');
document.getElementById('blogSummary').setAttribute('value','Blog '+summary);}}
}}
[edit] Using MediaWiki Ajax instead of MooTools
As of version 0.4.1, SimpleForms no longer requires the MooTools JavaScript framework. One of the main additions is the following snippet,
if ($wgUseAjax && $_REQUEST['action'] == 'ajax' && $_REQUEST['rs'] == 'wfSimpleFormsAjax') { $_REQUEST['action'] = 'render'; if (is_array($_REQUEST['rsargs'])) foreach ($_REQUEST['rsargs'] as $arg) if (preg_match('/^(.+?)=(.+)$/',$arg,$m)) $_REQUEST[$m[1]] = $m[2]; }
This allows us to use the sajax_do_call function from MediaWiki's ajax.js, but this works by requesting the AjaxDispatcher class to execute a function specified in the request and to return the results of the function. This is not quite the way SimpleForms needs it to work because the AjaxDispatcher is instantiated before any high-level MediaWiki objects have been instantiated, but SimpleForms needs to return the fully rendered page content with all extension activated etc.
The code above gets around this problem by detecting if incoming requests from sajax_do_call are specifying a function called "wfSimpleFormsAjax", and if so the action is changed to render so the request will no be handled by the AjaxDispatcher. The sajax_do_call argument list is shifted into the main $_REQUEST array as if it came from a normal GET or POST request. Note that there is actually no function called wfSimpleFormsAjax, it is just a dummy value used to identify the 'sajax_do_call request as one for SimpleForms to handle instead of the AjaxDispatcher.
Here's an example of using sajax_do_call with SimpleForms and sending a title parameter:
sajax_do_call('wfSimpleFormsAjax',['title=no-such-article'],document.getElementById('sajax-test'))
[edit] Change log
- Version 0.4.8 (2008-03-29): For Ajax, Radio and Checkbox values must be used only when they are 'checked'. --Danbrice 05:36, 29 March 2008 (UTC)
- Version 0.4.7 (2008-03-08): I/O support for mulitple attribute in select. —Sledged (talk) 00:45, 8 March 2008 (UTC)
- Version 0.4.6 (2007-11-08): Caching bug fix
- Version 0.4.5 (2007-10-27): Attempt bug fix - content still being returned from parser-cache when action=render on some installs
- Version 0.4.4 (2007-10-24): Bug fix - undefined index on line 53
- Version 0.4.3 (2007-10-22): Bug fix - content being returned from parser-cache when action=render on some installations - forced no-cache
- Version 0.4.2 (2007-10-08): Bug fix - needs var in JS-href for ajax links to work
- Version 0.4.1 (2007-10-04): No dependency on MooTools anymore!
- Version 0.4.0 (2007-10-04): Ajax links are now independent of MooTools, but not form-submit still requires it
- Version 0.3.13 (2007-10-03): Added support for ajax requests from MediaWiki's sajax_do_call function instead of MooTools
- Version 0.3.12 (2007-09-24): Slight bug in last adjustments which breaks MW1.11 fixed
- Version 0.3.11 (2007-09-22): Minor technical adjustments
- Version 0.3.10 (2007-09-19): Bug fixed which prevented forms from having only single inputs
- Version 0.3.9 (2007-09-03): Bail from processRequest() if title is special
- Version 0.3.8 (2007-09-01): Fixed bug preventing content from updating article when caction=replace
- Version 0.3.7 (2007-08-29): Use a unique-id for forms instead of counter as forms in ajax requests have conflicting id's
- Version 0.3.6 (2007-08-29): Remove the sf-prefix by default as it's causing trouble
- Version 0.3.5 (2007-08-27): Fixed bug preventing content action from being able to create new articles
- Version 0.3.3 (2007-07-24): Fixed a bug causing action=render to fail when used with content and no title
- Version 0.3.2 (2007-07-09): Removed special-page and #edit parser-function, SimpleForms will not be implementing these
- Version 0.3.0 (2007-07-07): Make action=render work with special pages and with article updates
- Version 0.2.6 (2007-06-28): Patch to allow form-submit to work properly in Extension:Wiklets while they're still iFrames
- Version 0.2.5 (2007-06-19): regexp parameter added
- Version 0.2.3 (2007-06-19): content without title works with action=raw (including optional templates=expand)
- Version 0.2.2 (2007-06-19): action=render added automatically for Ajax inputs, Ajax link inputs done
- Version 0.2.1 (2007-06-19): Allow <nowiki>'s around content
- Version 0.2.0 (2007-06-18): added Ajax functionality using MooTools
- Version 0.1.1 (2007-06-16): returnto parameter added
- Version 0.1.0 (2007-06-15): templates parameter working
- Version 0.0.9 (2007-06-11): Rendering of content without associated title working
- Version 0.0.3 (2007-05-10): Main form and input parser-functions working, ready for basic use
[edit] Todo & Plans
- Make interfacing forms with template definitions much easier
[edit] Bugs & Problems
- There's a bug which prevents the content parameter from being empty which is a problem if using with regexp to remove matching items.
- action=render is only working for some special pages (like Special:Version, but not others like allpages or DPL
- content is not working with edit yet
- It should use edit tokens, see API for discussion about this.
- Test ajax with request-prefix
[edit] See also
- OrganicDesign:SimpleForms cheatsheet - examples of using different input types
- API - the official MediaWiki API which is under development
- Mootools using Mootools with MediaWiki (Note that SimpleForms no longer uses MooTools)
- Manual:Edit token - why use edit tokens
- Extension:FormMailer - Use this to make SimpleForms into enquiry forms
- Attack of the Ajax form builders
- Extension:Semantic Forms - this is the best extension to use for interfacing with structured-data articles
- Using SMW and Simple Forms to produce user-friendly search forms

