Bootstrap Switch plugin

Estrusco edited this page Nov 24, 2016 · 1 revision
Clone this wiki locally

[HowTo] Bootstrap Switch plugin by marcobisio

See original post: https://github.com/volkanceylan/Serenity/issues/1439

Dear all, in this simple guide I'll explain how to add and use the Bootstrap Switch plugin (http://www.bootstrap-switch.org).

Here we go:

@Html.Stylesheet("~/Content/bootstrap-switch/bootstrap3/bootstrap-switch.css")
@Html.Script("~/Scripts/bootstrap-switch.js")
  • Create the Bootstrap switch widget:
namespace MyProject {
    @Serenity.Decorators.element('<input type="checkbox"/>')
    @Serenity.Decorators.registerClass([Serenity.IGetEditValue, Serenity.ISetEditValue])
    export class BSSwitchEditor
        extends Serenity.Widget<BootstrapSwitchOptions>
        implements Serenity.IGetEditValue, Serenity.ISetEditValue {

        constructor(element: JQuery, opt: BootstrapSwitchOptions) {
            super(element, opt);

            this.options.size = "mini";
            element.attr('type', 'checkbox').bootstrapSwitch(this.options);
        }

        public setEditValue(source: any, property: Serenity.PropertyItem): void {
            this.element.bootstrapSwitch('state', source[property.name]);
        }

        public getEditValue(property: Serenity.PropertyItem, target: any): void {
            target[property.name] = this.element.bootstrapSwitch('state');
        }
    }
    export interface BootstrapSwitchOptions {
        state?: boolean;
        size?: string;
        animate?: boolean;
        disabled?: boolean;
        readonly?: boolean;
        indeterminate?: boolean;
        invers?: boolean;
        radioAllOff?: boolean;
        onColor?: string;
        offColor?: string;
        onText?: string;
        offText?: string;
        labelText?: string;
        handleWidth?: string;
        labelWidth?: string;
        baseClass?: string;
        wrapperClass?: string;
        onInit?: any;
        onSwitchChange?: any;
    }
}
  • Just use in your row (Northwind Product here):
[DisplayName("Discontinued"), NotNull]
[BSSwitchEditor(OnText = "Yes", OffText = "No")]
public Boolean? Discontinued
{
    get { return Fields.Discontinued[this]; }
    set { Fields.Discontinued[this] = value; }
}

For set:

public setEditValue(source: any, property: Serenity.PropertyItem): void {
        if (this.element.hasClass('required')) this.element.removeClass('required');
        this.element.bootstrapSwitch('state', source[property.name]);
}

Hope it helps... That's all folks! Bye

Edit: still something to adjust if the field is required...I let you know

See original post: https://github.com/volkanceylan/Serenity/issues/1439