Skip to content

SelectField iter_choices() yield issue #45

@YKdvd

Description

@YKdvd

In WTForms, SelectFieldBase (which wtforms.SelectField inherits from) defines __iter__() to yield "_Option" instances - _Option is a Field subclass defined within SelectFieldBase to hold the options for the SelectField. To fill these _Option instances, __iter__() calls self.iter_choices, which it expects will yield a 3-tuple of (value, label, checked), where "checked" is a simple boolean indicating if the current field data value is equal to the option value, and so should be rendered as the currently selected option in the popup. This value is assigned into the _Option.checked attribute.

wtforms-components redefines the "iter_choices()" method, so that the third item of the 3-tuple it yields is not the simple boolean, but a 2-tuple with a coerce function and a data value, which is what __iter__() will now see. Internally wtforms handles this change since its widget knows about the revised output of iter_choices(). But the original WTForms __iter__() method doesn't, and assigns a bogus value to the "checked" attribute of the _Option instances it spits out.

Should wtforms-components have re-implemented SelectField.__iter__() so that it provides valid _Option fields if you iterate the SelectField? Perhaps there is no legitmate use for iterating through the options of a SelectField like this, but I was using it to add HTML "data-" attributes on the individual "option" items, and got bit by this - all options come out with the HTML "selected" attribute set.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions