def __init__(self, *args, **kwargs):
        environments = kwargs.pop("environments", [])
        current = kwargs.pop("current", None)

        super(EnvironmentSelectionForm, self).__init__(*args, **kwargs)

        # list of categories, ordered by name
        self.categories = []

        # maps category to set of elements
        self.elements_by_category = {}

        # maps environment ID to list of element IDs, ordered by category
        self.elementids_by_envid = {}

        # elements in current environment
        current_elements = []

        env_element_through_model = model.Environment.elements.through
        env_element_relationships = env_element_through_model.objects.filter(
            environment__in=environments).select_related()

        # first construct the ordered list of categories (and current elements)
        cat_set = set()
        for ee in env_element_relationships:
            cat_set.add(ee.element.category)
            if ee.environment.id == current:
                current_elements.append(ee.element)
        self.categories = sorted(cat_set, key=lambda c: c.name)

        num_categories = len(self.categories)

        # populate elements by category and environment
        for ee in env_element_relationships:
            byenv = self.elementids_by_envid.setdefault(
                ee.environment.id, [None] * num_categories)
            category_index = self.categories.index(ee.element.category)
            byenv[category_index] = ee.element.id

            bycat = self.elements_by_category.setdefault(
                ee.element.category, set())
            bycat.add(ee.element)

        # construct choice-field for each env type
        for category in self.categories:
            self.fields["category_{0}".format(category.id)] = forms.ChoiceField(
                choices=[("", "---------")] + [
                    (e.id, e.name) for e in sorted(
                        self.elements_by_category[category],
                        key=lambda e: e.name)
                    ],
                label=category.name,
                required=False)

        # set initial data based on current user environment
        for element in current_elements:
            field_name = "category_{0}".format(element.category.id)
            self.initial[field_name] = element.id
Accepts ``environments`` queryset and ``current`` env id.
dataset/ETHPy150Open mozilla/moztrap/moztrap/view/runtests/forms.py/EnvironmentSelectionForm.__init__