2

I am strugling to find resources that explain how to create custom widget with wtforms. I want to display a list of toggle buttons. So far I ve been able to create a list of checkboxes with

SelectMultipleFields: class PrecisionForm(FlaskForm): phone_number = StringField('Phone number', [validators.Length(min=4, max=25)]) contact_emails = SelectMultipleField( 'Contact emails', [at_least_one], choices=[], option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False) ) 

but now I want to modify my widget.CheckBoxInput() with my custom widget looking like :

<label class='switch'> <input type='checkbox'><span class='slider round'></span></label>

I would be very grateful if someone could explain step by step how to do that.

--UPDATE--

I found a way to achieve what I wanted to do but it seems pretty bad :

class ToggleButtonWidget(object): def __call__(self, field): html = '<label class="switch"><input type="checkbox" id={} name={} value={}><span class="slider round"></span></label>'.format(field.id, field.name, field.label.__dict__['text']) return HTMLString(html) 

especially this part : field.label.__dict__['text'] that I use to set the value of my checkbox (the field object from wtforms has no attribute value). Is there a better way ?

1 Answer 1

1

The styling of the input field should be done in the frontend. For example, you would have:

class CheckBoxWidget(Form): box1 = BooleanField() box2 = BooleanField() ... widget = FormField(CheckBoxWidget) 

And then in your html file you would have something like:

<div> form.widget.label("checkbox-class") form.widget("other-checkbox-class") </div> 

wrapped inside of your form.

Sign up to request clarification or add additional context in comments.

1 Comment

Styling should be left to the front end, but the OP is wanting to modify the structure to place the input inside the label. This is an ugly but common trick when using CSS to define alternate radio and checkbox controls.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.