Skip to content

Dynamic loading of ui.select options -> event handling error #4420

@platinops

Description

@platinops

Description

I was trying to create a custom element to dynamically load the items from a long list that I do not want to transfer entirely to the client.

from typing import List, Any, Optional
import re

from nicegui import ui, events

options = []
for letter in ["A", "B", "C"]:
    options += [f"Option {letter}-{i:05d}" for i in range(10)]


class FilteredSelect(ui.select):
    def __init__(
        self,
        options: List,
        label: Optional[str] = None,
        value: Any = None,
        max_items: int = 20,
    ) -> None:
        super().__init__(options=[], label=label, value=value, with_input=True)
        self.max_items = max_items
        self.all_options = options
        self.set_limited_options(options)
        self._props["input-debounce"] = 100
        self.on("input-value", self.handle_filter)

    def set_limited_options(self, options: List) -> List:
        if len(options) > self.max_items:
            options = options[: self.max_items]
            options.append("...")
        self.options = options

    def handle_filter(self, e: events.GenericEventArguments):
        search_value = str(e.args)
        regex_text = re.escape(f"{search_value}*").replace("\*", ".*")
        regex = re.compile(regex_text, re.IGNORECASE)
        options = [o for o in self.all_options if re.match(regex, str(o))]
        self.set_limited_options(options)
        self.update()


with ui.row():
    with ui.column():
        ui.select(options, label="Select a value", with_input=True).classes("w-40")
    with ui.column():
        FilteredSelect(options, label="Select a value", max_items=3).classes("w-40")

ui.run()

The idea is you can filter the items using a search string such as "Opt*B-0".

The filtering in itself works fine, but when I actually select the item, I get a list index out of range error. Is this a bug or is the above not the way to go about this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    analysisStatus: Requires team/community input🌳 advancedDifficulty: Requires deep knowledge of the topic

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions