flask-wtf
flask-wtf copied to clipboard
Add empty option in SelectField
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>
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.
Not exactly what I was hoping to...
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.
This would be pretty useful ++
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')])
Note that the text shown should also be supported by translation to other languages.
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
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.