HTMLForm: Add "cloner" type
authorBrad Jorsch <bjorsch@wikimedia.org>
Fri, 7 Mar 2014 16:03:32 +0000 (11:03 -0500)
committerOri.livneh <ori@wikimedia.org>
Fri, 2 May 2014 15:02:40 +0000 (15:02 +0000)
SecurePoll is going to need the ability to have a form for stuff like
"one or more admin usernames" and "one or more poll questions, each with
one or more options".

This change implements a generic field container that simply displays as
a <ul> followed by an "add more" button, with each <li> containing
various fields including a "remove" button.

Since this is only going to show up in SecurePoll to people creating a
poll (not to general users), the current design is functional but not
necessarily beautiful. Those interested in beauty are welcome to do so
in a followup change.

Change-Id: I46fad3971739ddc961259fe32eb6e1cd265a1c06

includes/AutoLoader.php
includes/htmlform/HTMLForm.php
includes/htmlform/HTMLFormField.php
includes/htmlform/HTMLFormFieldCloner.php [new file with mode: 0644]
languages/i18n/en.json
languages/i18n/qqq.json
maintenance/language/messages.inc
resources/src/mediawiki/mediawiki.htmlform.js

index d7416ec..bfee420 100644 (file)
@@ -89,6 +89,7 @@ $wgAutoloadLocalClasses = array(
        'HTMLButtonField' => 'includes/htmlform/HTMLButtonField.php',
        'HTMLCheckField' => 'includes/htmlform/HTMLCheckField.php',
        'HTMLCheckMatrix' => 'includes/htmlform/HTMLCheckMatrix.php',
+       'HTMLFormFieldCloner' => 'includes/htmlform/HTMLFormFieldCloner.php',
        'HTMLEditTools' => 'includes/htmlform/HTMLEditTools.php',
        'HTMLFloatField' => 'includes/htmlform/HTMLFloatField.php',
        'HTMLForm' => 'includes/htmlform/HTMLForm.php',
index 019eb2b..01f3ab7 100644 (file)
@@ -117,6 +117,7 @@ class HTMLForm extends ContextSource {
                'hidden' => 'HTMLHiddenField',
                'edittools' => 'HTMLEditTools',
                'checkmatrix' => 'HTMLCheckMatrix',
+               'cloner' => 'HTMLFormFieldCloner',
                // HTMLTextField will output the correct type="" attribute automagically.
                // There are about four zillion other HTML5 input types, like range, but
                // we don't use those at the moment, so no point in adding all of them.
@@ -155,6 +156,7 @@ class HTMLForm extends ContextSource {
 
        protected $mTitle;
        protected $mMethod = 'post';
+       protected $mWasSubmitted = false;
 
        /**
         * Form action URL. false means we will use the URL to set Title
@@ -411,6 +413,7 @@ class HTMLForm extends ContextSource {
                }
 
                if ( $submit ) {
+                       $this->mWasSubmitted = true;
                        $result = $this->trySubmit();
                }
 
@@ -445,6 +448,19 @@ class HTMLForm extends ContextSource {
         *     display.
         */
        function trySubmit() {
+               $this->mWasSubmitted = true;
+
+               # Check for cancelled submission
+               foreach ( $this->mFlatFields as $fieldname => $field ) {
+                       if ( !empty( $field->mParams['nodata'] ) ) {
+                               continue;
+                       }
+                       if ( $field->cancelSubmit( $this->mFieldData[$fieldname], $this->mFieldData ) ) {
+                               $this->mWasSubmitted = false;
+                               return false;
+                       }
+               }
+
                # Check for validation
                foreach ( $this->mFlatFields as $fieldname => $field ) {
                        if ( !empty( $field->mParams['nodata'] ) ) {
@@ -470,10 +486,28 @@ class HTMLForm extends ContextSource {
                $data = $this->filterDataForSubmit( $this->mFieldData );
 
                $res = call_user_func( $callback, $data, $this );
+               if ( $res === false ) {
+                       $this->mWasSubmitted = false;
+               }
 
                return $res;
        }
 
+       /**
+        * Test whether the form was considered to have been submitted or not, i.e.
+        * whether the last call to tryAuthorizedSubmit or trySubmit returned
+        * non-false.
+        *
+        * This will return false until HTMLForm::tryAuthorizedSubmit or
+        * HTMLForm::trySubmit is called.
+        *
+        * @since 1.23
+        * @return bool
+        */
+       function wasSubmitted() {
+               return $this->mWasSubmitted;
+       }
+
        /**
         * Set a callback to a function to do something with the form
         * once it's been successfully validated.
index 204020d..0e1860b 100644 (file)
@@ -241,15 +241,30 @@ abstract class HTMLFormField {
                return $this->isHiddenRecurse( $alldata, $this->mHideIf );
        }
 
+       /**
+        * Override this function if the control can somehow trigger a form
+        * submission that shouldn't actually submit the HTMLForm.
+        *
+        * @since 1.23
+        * @param string|array $value The value the field was submitted with
+        * @param array $alldata The data collected from the form
+        *
+        * @return bool true to cancel the submission
+        */
+       function cancelSubmit( $value, $alldata ) {
+               return false;
+       }
+
        /**
         * Override this function to add specific validation checks on the
         * field input.  Don't forget to call parent::validate() to ensure
         * that the user-defined callback mValidationCallback is still run
         *
-        * @param string $value The value the field was submitted with
+        * @param string|array $value The value the field was submitted with
         * @param array $alldata The data collected from the form
         *
-        * @return bool|string true on success, or String error to display.
+        * @return bool|string true on success, or String error to display, or
+        *   false to fail validation without displaying an error.
         */
        function validate( $value, $alldata ) {
                if ( $this->isHidden( $alldata ) ) {
@@ -356,6 +371,7 @@ abstract class HTMLFormField {
                }
 
                $validName = Sanitizer::escapeId( $this->mName );
+               $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
                if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
                        throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
                }
@@ -631,9 +647,7 @@ abstract class HTMLFormField {
        public function getErrorsAndErrorClass( $value ) {
                $errors = $this->validate( $value, $this->mParent->mFieldData );
 
-               if ( $errors === true ||
-                       ( !$this->mParent->getRequest()->wasPosted() && $this->mParent->getMethod() === 'post' )
-               ) {
+               if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
                        $errors = '';
                        $errorClass = '';
                } else {
diff --git a/includes/htmlform/HTMLFormFieldCloner.php b/includes/htmlform/HTMLFormFieldCloner.php
new file mode 100644 (file)
index 0000000..597a03f
--- /dev/null
@@ -0,0 +1,380 @@
+<?php
+
+/**
+ * A container for HTMLFormFields that allows for multiple copies of the set of
+ * fields to be displayed to and entered by the user.
+ *
+ * Recognized parameters, besides the general ones, include:
+ *   fields - HTMLFormField descriptors for the subfields this cloner manages.
+ *     The format is just like for the HTMLForm. A field with key 'delete' is
+ *     special: it must have type = submit and will serve to delete the group
+ *     of fields.
+ *   required - If specified, at least one group of fields must be submitted.
+ *   format - HTMLForm display format to use when displaying the subfields:
+ *     'table', 'div', or 'raw'.
+ *   row-legend - If non-empty, each group of subfields will be enclosed in a
+ *     fieldset. The value is the name of a message key to use as the legend.
+ *   create-button-message - Message key to use as the text of the button to
+ *     add an additional group of fields.
+ *   delete-button-message - Message key to use as the text of automatically-
+ *     generated 'delete' button. Ignored if 'delete' is included in 'fields'.
+ *
+ * In the generated HTML, the subfields will be named along the lines of
+ * "clonerName[index][fieldname]", with ids "clonerId--index--fieldid". 'index'
+ * may be a number or an arbitrary string, and may likely change when the page
+ * is resubmitted. Cloners may be nested, resulting in field names along the
+ * lines of "cloner1Name[index1][cloner2Name][index2][fieldname]" and
+ * corresponding ids.
+ *
+ * Use of cloner may result in submissions of the page that are not submissions
+ * of the HTMLForm, when non-JavaScript clients use the create or remove buttons.
+ *
+ * The result is an array, with values being arrays mapping subfield names to
+ * their values. On non-HTMLForm-submission page loads, there may also be
+ * additional (string) keys present with other types of values.
+ *
+ * @since 1.23
+ */
+class HTMLFormFieldCloner extends HTMLFormField {
+       private static $counter = 0;
+
+       /**
+        * @var string String uniquely identifying this cloner instance and
+        * unlikely to exist otherwise in the generated HTML, while still being
+        * valid as part of an HTML id.
+        */
+       protected $uniqueId;
+
+       public function __construct( $params ) {
+               $this->uniqueId = get_class( $this ) . ++self::$counter . 'x';
+               parent::__construct( $params );
+
+               if ( empty( $this->mParams['fields'] ) || !is_array( $this->mParams['fields'] ) ) {
+                       throw new MWException( 'HTMLFormFieldCloner called without any fields' );
+               }
+
+               // Make sure the delete button, if explicitly specified, is sane
+               if ( isset( $this->mParams['fields']['delete'] ) ) {
+                       $class = 'mw-htmlform-cloner-delete-button';
+                       $info = $this->mParams['fields']['delete'] + array(
+                               'cssclass' => $class
+                       );
+                       unset( $info['name'], $info['class'] );
+
+                       if ( !isset( $info['type'] ) || $info['type'] !== 'submit' ) {
+                               throw new MWException(
+                                       'HTMLFormFieldCloner delete field, if specified, must be of type "submit"'
+                               );
+                       }
+
+                       if ( !in_array( $class, explode( ' ', $info['cssclass'] ) ) ) {
+                               $info['cssclass'] .= " $class";
+                       }
+
+                       $this->mParams['fields']['delete'] = $info;
+               }
+       }
+
+       /**
+        * Create the HTMLFormFields that go inside this element, using the
+        * specified key.
+        *
+        * @param string $key Array key under which these fields should be named
+        * @return HTMLFormFields[]
+        */
+       protected function createFieldsForKey( $key ) {
+               $fields = array();
+               foreach ( $this->mParams['fields'] as $fieldname => $info ) {
+                       $name = "{$this->mName}[$key][$fieldname]";
+                       if ( isset( $info['name'] ) ) {
+                               $info['name'] = "{$this->mName}[$key][{$info['name']}]";
+                       } else {
+                               $info['name'] = $name;
+                       }
+                       if ( isset( $info['id'] ) ) {
+                               $info['id'] = Sanitizer::escapeId( "{$this->mID}--$key--{$info['id']}" );
+                       } else {
+                               $info['id'] = Sanitizer::escapeId( "{$this->mID}--$key--$fieldname" );
+                       }
+                       $field = HTMLForm::loadInputFromParameters( $name, $info );
+                       $field->mParent = $this->mParent;
+                       $fields[$fieldname] = $field;
+               }
+               return $fields;
+       }
+
+       /**
+        * Re-key the specified values array to match the names applied by
+        * createFieldsForKey().
+        *
+        * @param string $key Array key under which these fields should be named
+        * @param array $values Values array from the request
+        * @return array
+        */
+       protected function rekeyValuesArray( $key, $values ) {
+               $data = array();
+               foreach ( $values as $fieldname => $value ) {
+                       $name = "{$this->mName}[$key][$fieldname]";
+                       $data[$name] = $value;
+               }
+               return $data;
+       }
+
+       protected function needsLabel() {
+               return false;
+       }
+
+       public function loadDataFromRequest( $request ) {
+               // It's possible that this might be posted with no fields. Detect that
+               // by looking for an edit token.
+               if ( !$request->getCheck( 'wpEditToken' ) && $request->getArray( $this->mName ) === null ) {
+                       return $this->getDefault();
+               }
+
+               $values = $request->getArray( $this->mName );
+               if ( $values === null ) {
+                       $values = array();
+               }
+
+               $ret = array();
+               foreach ( $values as $key => $value ) {
+                       if ( $key === 'create' || isset( $value['delete'] ) ) {
+                               $ret['nonjs'] = 1;
+                               continue;
+                       }
+
+                       // Add back in $request->getValues() so things that look for e.g.
+                       // wpEditToken don't fail.
+                       $data = $this->rekeyValuesArray( $key, $value ) + $request->getValues();
+
+                       $fields = $this->createFieldsForKey( $key );
+                       $subrequest = new DerivativeRequest( $request, $data, $request->wasPosted() );
+                       $row = array();
+                       foreach ( $fields as $fieldname => $field ) {
+                               if ( !empty( $field->mParams['nodata'] ) ) {
+                                       continue;
+                               } elseif ( !empty( $field->mParams['disabled'] ) ) {
+                                       $row[$fieldname] = $field->getDefault();
+                               } else {
+                                       $row[$fieldname] = $field->loadDataFromRequest( $subrequest );
+                               }
+                       }
+                       $ret[] = $row;
+               }
+
+               if ( isset( $values['create'] ) ) {
+                       // Non-JS client clicked the "create" button.
+                       $fields = $this->createFieldsForKey( $this->uniqueId );
+                       $row = array();
+                       foreach ( $fields as $fieldname => $field ) {
+                               if ( !empty( $field->mParams['nodata'] ) ) {
+                                       continue;
+                               } else {
+                                       $row[$fieldname] = $field->getDefault();
+                               }
+                       }
+                       $ret[] = $row;
+               }
+
+               return $ret;
+       }
+
+       public function getDefault() {
+               $ret = parent::getDefault();
+
+               // The default default is one entry with all subfields at their
+               // defaults.
+               if ( $ret === null ) {
+                       $fields = $this->createFieldsForKey( $this->uniqueId );
+                       $row = array();
+                       foreach ( $fields as $fieldname => $field ) {
+                               if ( !empty( $field->mParams['nodata'] ) ) {
+                                       continue;
+                               } else {
+                                       $row[$fieldname] = $field->getDefault();
+                               }
+                       }
+                       $ret = array( $row );
+               }
+
+               return $ret;
+       }
+
+       public function cancelSubmit( $values, $alldata ) {
+               if ( isset( $values['nonjs'] ) ) {
+                       return true;
+               }
+
+               foreach ( $values as $key => $value ) {
+                       $fields = $this->createFieldsForKey( $key );
+                       foreach ( $fields as $fieldname => $field ) {
+                               if ( !empty( $field->mParams['nodata'] ) ) {
+                                       continue;
+                               }
+                               if ( $field->cancelSubmit( $value[$fieldname], $alldata ) ) {
+                                       return true;
+                               }
+                       }
+               }
+
+               return parent::cancelSubmit( $values, $alldata );
+       }
+
+       public function validate( $values, $alldata ) {
+               if ( isset( $this->mParams['required'] )
+                       && $this->mParams['required'] !== false
+                       && !$values
+               ) {
+                       return $this->msg( 'htmlform-cloner-required' )->parseAsBlock();
+               }
+
+               if ( isset( $values['nonjs'] ) ) {
+                       // The submission was a non-JS create/delete click, so fail
+                       // validation in case cancelSubmit() somehow didn't already handle
+                       // it.
+                       return false;
+               }
+
+               foreach ( $values as $key => $value ) {
+                       $fields = $this->createFieldsForKey( $key );
+                       foreach ( $fields as $fieldname => $field ) {
+                               if ( !empty( $field->mParams['nodata'] ) ) {
+                                       continue;
+                               }
+                               $ok = $field->validate( $value[$fieldname], $alldata );
+                               if ( $ok !== true ) {
+                                       return false;
+                               }
+                       }
+               }
+
+               return parent::validate( $values, $alldata );
+       }
+
+       /**
+        * Get the input HTML for the specified key.
+        *
+        * @param string $key Array key under which the fields should be named
+        * @param array $values
+        * @return string
+        */
+       protected function getInputHTMLForKey( $key, $values ) {
+               $displayFormat = isset( $this->mParams['format'] )
+                       ? $this->mParams['format']
+                       : $this->mParent->getDisplayFormat();
+
+               switch ( $displayFormat ) {
+                       case 'table':
+                               $getFieldHtmlMethod = 'getTableRow';
+                               break;
+                       case 'vform':
+                               // Close enough to a div.
+                               $getFieldHtmlMethod = 'getDiv';
+                               break;
+                       default:
+                               $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
+               }
+
+               $html = '';
+               $hasLabel = false;
+
+               $fields = $this->createFieldsForKey( $key );
+               foreach ( $fields as $fieldname => $field ) {
+                       $v = ( empty( $field->mParams['nodata'] ) && $values !== null )
+                               ? $values[$fieldname]
+                               : $field->getDefault();
+                       $html .= $field->$getFieldHtmlMethod( $v );
+
+                       $labelValue = trim( $field->getLabel() );
+                       if ( $labelValue != '&#160;' && $labelValue !== '' ) {
+                               $hasLabel = true;
+                       }
+               }
+
+               if ( !isset( $fields['delete'] ) ) {
+                       $name = "{$this->mName}[$key][delete]";
+                       $label = isset( $this->mParams['delete-button-message'] )
+                               ? $this->mParams['delete-button-message']
+                               : 'htmlform-cloner-delete';
+                       $field = HTMLForm::loadInputFromParameters( $name, array(
+                               'type' => 'submit',
+                               'name' => $name,
+                               'id' => Sanitizer::escapeId( "{$this->mID}--$key--delete" ),
+                               'cssclass' => 'mw-htmlform-cloner-delete-button',
+                               'default' => $this->msg( $label )->text(),
+                       ) );
+                       $v = $field->getDefault();
+
+                       if ( $displayFormat === 'table' ) {
+                               $html .= $field->$getFieldHtmlMethod( $v );
+                       } else {
+                               $html .= $field->getInputHTML( $v );
+                       }
+               }
+
+               if ( $displayFormat !== 'raw' ) {
+                       $classes = array(
+                               'mw-htmlform-cloner-row',
+                       );
+
+                       if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
+                               $classes[] = 'mw-htmlform-nolabel';
+                       }
+
+                       $attribs = array(
+                               'class' => implode( ' ', $classes ),
+                       );
+
+                       if ( $displayFormat === 'table' ) {
+                               $html = Html::rawElement( 'table',
+                                       $attribs,
+                                       Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
+                       } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
+                               $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
+                       }
+               }
+
+               if ( !empty( $this->mParams['row-legend'] ) ) {
+                       $legend = $this->msg( $this->mParams['row-legend'] )->text();
+                       $html = Xml::fieldset( $legend, $html );
+               }
+
+               return $html;
+       }
+
+       public function getInputHTML( $values ) {
+               $html = '';
+
+               foreach ( (array)$values as $key => $value ) {
+                       if ( $key === 'nonjs' ) {
+                               continue;
+                       }
+                       $html .= Html::rawElement( 'li', array( 'class' => 'mw-htmlform-cloner-li' ),
+                               $this->getInputHTMLForKey( $key, $value )
+                       );
+               }
+
+               $template = $this->getInputHTMLForKey( $this->uniqueId, null );
+               $html = Html::rawElement( 'ul', array(
+                       'id' => "mw-htmlform-cloner-list-{$this->mID}",
+                       'class' => 'mw-htmlform-cloner-ul',
+                       'data-template' => $template,
+                       'data-unique-id' => $this->uniqueId,
+               ), $html );
+
+               $name = "{$this->mName}[create]";
+               $label = isset( $this->mParams['create-button-message'] )
+                       ? $this->mParams['create-button-message']
+                       : 'htmlform-cloner-create';
+               $field = HTMLForm::loadInputFromParameters( $name, array(
+                       'type' => 'submit',
+                       'name' => $name,
+                       'id' => Sanitizer::escapeId( "{$this->mID}--create" ),
+                       'cssclass' => 'mw-htmlform-cloner-create-button',
+                       'default' => $this->msg( $label )->text(),
+               ) );
+               $html .= $field->getInputHTML( $field->getDefault() );
+
+               return $html;
+       }
+}
index 54d550a..1f5fe37 100644 (file)
     "htmlform-no": "No",
     "htmlform-yes": "Yes",
     "htmlform-chosen-placeholder": "Select an option",
+       "htmlform-cloner-create": "Add more",
+       "htmlform-cloner-delete": "Remove",
+       "htmlform-cloner-required": "At least one value is required.",
     "sqlite-has-fts": "$1 with full-text search support",
     "sqlite-no-fts": "$1 without full-text search support",
     "logentry-delete-delete": "$1 {{GENDER:$2|deleted}} page $3",
index 58a2a64..028d155 100644 (file)
        "htmlform-no": "Used in form, such as with radio buttons, for generic yes / no questions.\n{{Identical|No}}",
        "htmlform-yes": "Used in form, such as with radio buttons, for generic yes / no questions.\n{{Identical|Yes}}",
        "htmlform-chosen-placeholder": "Used as initial placeholder text in select multiple \"chosen\" input boxes",
+       "htmlform-cloner-create": "Used as the text for the button that adds a row to a multi-input HTML form element\n\nSee also:\n* {{msg-mw|htmlform-cloner-delete}}\n{{msg-mw|htmlform-cloner-required}}",
+       "htmlform-cloner-delete": "Used as the text for the button that removes a row from a multi-input HTML form element\n\nSee also:\n* {{msg-mw|htmlform-cloner-create}}\n{{msg-mw|htmlform-cloner-required}}",
+       "htmlform-cloner-required": "Used as an error message in HTML forms.\n\nSee also:\n* {{msg-mw|htmlform-required}}\n{{msg-mw|htmlform-cloner-create}}\n{{msg-mw|htmlform-cloner-delete}}",
        "sqlite-has-fts": "Shown on [[Special:Version]].\nParameters:\n* $1 - version",
        "sqlite-no-fts": "Shown on [[Special:Version]].\nParameters:\n* $1 - version",
        "logentry-delete-delete": "{{Logentry|[[Special:Log/delete]]}}",
index 500d7de..62d1fa6 100644 (file)
@@ -3851,6 +3851,9 @@ $wgMessageStructure = array(
                'htmlform-no',
                'htmlform-yes',
                'htmlform-chosen-placeholder',
+               'htmlform-cloner-create',
+               'htmlform-cloner-delete',
+               'htmlform-cloner-required',
        ),
        'sqlite' => array(
                'sqlite-has-fts',
index def29fc..f7aa7f8 100644 (file)
@@ -5,6 +5,8 @@
  */
 ( function ( mw, $ ) {
 
+       var cloneCounter = 0;
+
        /**
         * Helper function for hide-if to find the nearby form field.
         *
                        } );
        };
 
-       $( function () {
+       function enhance( $root ) {
 
                // Animate the SelectOrOther fields, to only show the text field when
                // 'other' is selected.
-               $( '.mw-htmlform-select-or-other' ).liveAndTestAtStart( function ( instant ) {
-                       var $other = $( '#' + $( this ).attr( 'id' ) + '-other' );
+               $root.find( '.mw-htmlform-select-or-other' ).liveAndTestAtStart( function ( instant ) {
+                       var $other = $root.find( '#' + $( this ).attr( 'id' ) + '-other' );
                        $other = $other.add( $other.siblings( 'br' ) );
                        if ( $( this ).val() === 'other' ) {
                                $other.goIn( instant );
                } );
 
                // Set up hide-if elements
-               $( '.mw-htmlform-hide-if' ).each( function () {
+               $root.find( '.mw-htmlform-hide-if' ).each( function () {
                        var $el = $( this ),
                                spec = $el.data( 'hideIf' ),
                                v, $fields, test, func;
                        func();
                } );
 
-       } );
+               function addMulti( $oldContainer, $container ) {
+                       var name = $oldContainer.find( 'input:first-child' ).attr( 'name' ),
+                               oldClass = ( ' ' + $oldContainer.attr( 'class' ) + ' ' ).replace( /(mw-htmlform-field-HTMLMultiSelectField|mw-chosen)/g, '' ),
+                               $select = $( '<select>' ),
+                               dataPlaceholder = mw.message( 'htmlform-chosen-placeholder' );
+                       oldClass = $.trim( oldClass );
+                       $select.attr( {
+                               name: name,
+                               multiple: 'multiple',
+                               'data-placeholder': dataPlaceholder.plain(),
+                               'class': 'htmlform-chzn-select mw-input ' + oldClass
+                       } );
+                       $oldContainer.find( 'input' ).each( function () {
+                               var $oldInput = $( this ),
+                               checked = $oldInput.prop( 'checked' ),
+                               $option = $( '<option>' );
+                               $option.prop( 'value', $oldInput.prop( 'value' ) );
+                               if ( checked ) {
+                                       $option.prop( 'selected', true );
+                               }
+                               $option.text( $oldInput.prop( 'value' ) );
+                               $select.append( $option );
+                       } );
+                       $container.append( $select );
+               }
 
-       function addMulti( $oldContainer, $container ) {
-               var name = $oldContainer.find( 'input:first-child' ).attr( 'name' ),
-                       oldClass = ( ' ' + $oldContainer.attr( 'class' ) + ' ' ).replace( /(mw-htmlform-field-HTMLMultiSelectField|mw-chosen)/g, '' ),
-                       $select = $( '<select>' ),
-                       dataPlaceholder = mw.message( 'htmlform-chosen-placeholder' );
-               oldClass = $.trim( oldClass );
-               $select.attr( {
-                       name: name,
-                       multiple: 'multiple',
-                       'data-placeholder': dataPlaceholder.plain(),
-                       'class': 'htmlform-chzn-select mw-input ' + oldClass
-               } );
-               $oldContainer.find( 'input' ).each( function () {
-                       var $oldInput = $( this ),
-                       checked = $oldInput.prop( 'checked' ),
-                       $option = $( '<option>' );
-                       $option.prop( 'value', $oldInput.prop( 'value' ) );
-                       if ( checked ) {
-                               $option.prop( 'selected', true );
+               function convertCheckboxesToMulti( $oldContainer, type ) {
+                       var $fieldLabel = $( '<td>' ),
+                       $td = $( '<td>' ),
+                       $fieldLabelText = $( '<label>' ),
+                       $container;
+                       if ( type === 'tr' ) {
+                               addMulti( $oldContainer, $td );
+                               $container = $( '<tr>' );
+                               $container.append( $td );
+                       } else if ( type === 'div' ) {
+                               $fieldLabel = $( '<div>' );
+                               $container = $( '<div>' );
+                               addMulti( $oldContainer, $container );
                        }
-                       $option.text( $oldInput.prop( 'value' ) );
-                       $select.append( $option );
-               } );
-               $container.append( $select );
-       }
-
-       function convertCheckboxesToMulti( $oldContainer, type ) {
-               var $fieldLabel = $( '<td>' ),
-               $td = $( '<td>' ),
-               $fieldLabelText = $( '<label>' ),
-               $container;
-               if ( type === 'tr' ) {
-                       addMulti( $oldContainer, $td );
-                       $container = $( '<tr>' );
-                       $container.append( $td );
-               } else if ( type === 'div' ) {
-                       $fieldLabel = $( '<div>' );
-                       $container = $( '<div>' );
-                       addMulti( $oldContainer, $container );
+                       $fieldLabel.attr( 'class', 'mw-label' );
+                       $fieldLabelText.text( $oldContainer.find( '.mw-label label' ).text() );
+                       $fieldLabel.append( $fieldLabelText );
+                       $container.prepend( $fieldLabel );
+                       $oldContainer.replaceWith( $container );
+                       return $container;
                }
-               $fieldLabel.attr( 'class', 'mw-label' );
-               $fieldLabelText.text( $oldContainer.find( '.mw-label label' ).text() );
-               $fieldLabel.append( $fieldLabelText );
-               $container.prepend( $fieldLabel );
-               $oldContainer.replaceWith( $container );
-               return $container;
-       }
 
-       if ( $( '.mw-chosen' ).length ) {
-               mw.loader.using( 'jquery.chosen', function () {
-                       $( '.mw-chosen' ).each( function () {
-                               var type = this.nodeName.toLowerCase(),
-                                       $converted = convertCheckboxesToMulti( $( this ), type );
-                               $converted.find( '.htmlform-chzn-select' ).chosen( { width: 'auto' } );
+               if ( $root.find( '.mw-chosen' ).length ) {
+                       mw.loader.using( 'jquery.chosen', function () {
+                               $root.find( '.mw-chosen' ).each( function () {
+                                       var type = this.nodeName.toLowerCase(),
+                                               $converted = convertCheckboxesToMulti( $( this ), type );
+                                       $converted.find( '.htmlform-chzn-select' ).chosen( { width: 'auto' } );
+                               } );
                        } );
-               } );
-       }
+               }
 
-       $( function () {
-               var $matrixTooltips = $( '.mw-htmlform-matrix .mw-htmlform-tooltip' );
+               var $matrixTooltips = $root.find( '.mw-htmlform-matrix .mw-htmlform-tooltip' );
                if ( $matrixTooltips.length ) {
                        mw.loader.using( 'jquery.tipsy', function () {
                                $matrixTooltips.tipsy( { gravity: 's' } );
                        } );
                }
+
+               // Add/remove cloner clones without having to resubmit the form
+               $root.find( '.mw-htmlform-cloner-delete-button' ).click( function ( ev ) {
+                       ev.preventDefault();
+                       $( this ).closest( 'li.mw-htmlform-cloner-li' ).remove();
+               } );
+
+               $root.find( '.mw-htmlform-cloner-create-button' ).click( function ( ev ) {
+                       var $ul, $li, html;
+
+                       ev.preventDefault();
+
+                       $ul = $( this ).prev( 'ul.mw-htmlform-cloner-ul' );
+
+                       html = $ul.data( 'template' ).replace(
+                               $ul.data( 'uniqueId' ), 'clone' + ( ++cloneCounter ), 'g'
+                       );
+
+                       $li = $( '<li>' )
+                               .addClass( 'mw-htmlform-cloner-li' )
+                               .html( html )
+                               .appendTo( $ul );
+
+                       enhance( $li );
+               } );
+
+               mw.hook( 'htmlform.enhance' ).fire( $root );
+
+       }
+
+       $( function () {
+               enhance( $( document ) );
        } );
 
        /**