flask-wtf icon indicating copy to clipboard operation
flask-wtf copied to clipboard

Add empty option in SelectField

Open anselal opened this issue 6 years ago • 5 comments

Hi there,

is there a way to add an empty option to a Selectfield ? The only way I found is to add this to the choices before your actual choices:

[("", "-- select an option --")]

But this requires validation on the backend since this option should be disabled by default.

How can I disable this option so that the rendered tag would be like:

<option disabled="" selected="" value=""> -- select an option --</option>

anselal avatar Oct 05 '18 09:10 anselal

my way is: first: set default on form filed second: use '+' to add other option.

# form.py
class TestForm(FlaskForm):
    dropdownlist = SelectField('dropdownlist')

# view.py
@app.route('/your_route')    
def your_function():
    form = TestForm()
    select_option = Model.query.with_entities('key', 'value').all()

    form.dropdownlist.default = [('0', '-- select an option --')] + select_option
    return ...

of course you can add SelectField's option in Form init. Then while i insert into database, i will change 0 to None, if you set column null=True.

shaoeChen avatar Feb 22 '19 03:02 shaoeChen

Not exactly what I was hoping to...

anselal avatar Feb 22 '19 06:02 anselal

If you are using an ORM (sqlalchemy/django) then the wtforms QuerySelectField from the relevant wtforms extension have an allow_blank argument, where if True adds a blank field automatically.

E.g.:

from wtforms.ext.sqlalchemy.fields import QuerySelectField
class AForm(Form):
    category = QuerySelectField(
        query_factory=lambda: Category.query, 
        allow_blank=True
    )

It hard to look past if you are already querying through ORM to get select options.

Although the sqlalchemy extension is on the way out, to be replaced by WTForms-Alchemy in 3.0.

peterschutt avatar May 02 '19 01:05 peterschutt

This would be pretty useful ++

Uzay-G avatar May 20 '21 15:05 Uzay-G

My workaround for this was to include a custom validation function to not allow the first option, which might be something like "-- select an option --". I know this is not exactly what you were looking for and also 4 years late, but I hope this helps somebody haha

# form.py
class MyForm(FlaskForm):
    def validate_option(self, option_to_check):
        if option_to_check == "-- select an option --":
            raise ValidationError("Please select a role.")

     option = SelectField(label="Choose an option", choices=[('-- select an option --'), ('Option 1'), ('Option 2'), ('Option 3'), 
    ('Other')])

marrocelli avatar May 17 '22 00:05 marrocelli

Note that the text shown should also be supported by translation to other languages.

PanderMusubi avatar Nov 21 '22 10:11 PanderMusubi

The best way for disable an option or 'validate' a select field its the following:

the_field = SelectField(
    'The Field',
    choices=[('', 'Select any'), ('more_options', 'More Options')],
    validators=[InputRequired()],
    default=''
    )

Note: Add these imports

from wtforms import SelectField
from wtforms.validators import InputRequired

vvalenzuela96 avatar Dec 16 '22 16:12 vvalenzuela96

Disabling the option with a HTML disabled attribute will come with https://github.com/wtforms/wtforms/pull/739 You should still validate your field with InputRequired() though.

azmeuk avatar Jan 13 '23 16:01 azmeuk