Skip to content

Registering your own custom form builder

bcardarella edited this page May 17, 2011 · 5 revisions

Until there's a better interface to register your own builders, you can do it this way.

If you create a form builder and use that (let's say your inherited this CustomFormBuilder from SimpleForm::FormBuilder), you'll need to "register" this builder in the rails.validations.js file.

If you don't register it, you'll get errors that has something to do with clientSideValidations.formBuilders[settings.type].

To register this CustomFormBuilder, you first need to add a new js file rails.validations.customFormBuilders.js and require it in your layout. Then simple add the following:

  // ...
    'SimpleForm::FormBuilder': {
      // ...
    },
    'CustomFormBuilder': {
      add: function(element, settings, message) {
        if (element.data('valid') !== false) {
          var wrapper = element.closest(settings.wrapper_tag);
          wrapper.addClass(settings.wrapper_error_class);
          var errorElement = $('<' + settings.error_tag + ' class="' + settings.error_class + '">' + message + '</' + settings.error_tag + '>');
          wrapper.append(errorElement);
        } else {
          element.parent().find(settings.error_tag + '.' + settings.error_class).text(message);
        }
      },
      remove: function(element, settings) {
        var wrapper = element.closest(settings.wrapper_tag + '.' + settings.wrapper_error_class);
        wrapper.removeClass(settings.wrapper_error_class);
        var errorElement = wrapper.find(settings.error_tag + '.' + settings.error_class);
        errorElement.remove();
      }
    },
    'Formtastic::SemanticFormBuilder': {
      // ...
    }
  // ...

In this particular case, it was exactly like the SimpleForm::FormBuilder entry, since CustomFormBuilder inherits from that and changed the resulting HTML only slightly. If your custom form builder is radically different, you will have to edit the js accordingly.

Clone this wiki locally