Jump to content

Manual:Enabling autocomplete in a form

From mediawiki.org
Note: this is intended for developers. You may be looking for Manual:Enabling autocomplete in search box

If you want to add suggestion of page titles to a form using an extension, it's simple to do. First, design your form. Make sure you set a unique id on the field you want to fill. The following JavaScript should do what you need, and it has extra comments to explain everything. This example is used in Extension:MassMessage.

Example

[edit]

In MassMessage/ext.MassMessage.autocomplete.js:

/**
 * Add autocomplete suggestions to any input.
 * @author Legoktm
 * Mainly from http://jqueryui.com/autocomplete/
 * and resources/mediawiki/mediawiki.searchSuggest.js
 */

( function ( mw, $ ) {
    $( function () {
        // mw-massmessage-form-spamlist is the id of the field to autocomplete
        $( '#mw-massmessage-form-spamlist' ).autocomplete( {
            source: function( request, response ) {
                // Create a new Api object (see [[RL/DM#mediawiki.api]]
                var api = new mw.Api();
                // Start a "GET" request
                api.get( {
                    action: 'opensearch',
                    search: request.term, // This is the current value of the user's input
                    suggest: ''
                } ).done( function ( data ) {
                    response( data[1] ); // set the results as the autocomplete options
                } );
            }
        } );
    } );
}( mediaWiki, jQuery ) );

Now in MassMessage/MassMessage.php (the main extension file):

$wgResourceModules['ext.MassMessage.special'] = array(
	'scripts' => array(
		'ext.MassMessage.autocomplete.js',
	),
	'dependencies' => array(
		'jquery.ui.autocomplete'
	),
	'localBasePath' => __DIR__,
	'remoteExtPath' => 'MassMessage',
);

Finally, in your special page, you need to add a call to $this->getOutput()->addModules( 'ext.MassMessage.special' );.

Yay!

[edit]