Add suggested_value helper for FlowHandler (#82491)

* Add suggested_value helper for ConfigFlow

* Move helper function to FlowHandler

* Rename and adjust docstring

* Fix rebase
pull/82909/head
epenet 2022-11-29 10:16:01 +01:00 committed by GitHub
parent 53e05dec02
commit 724a79a8e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 19 deletions

View File

@ -4,6 +4,7 @@ from __future__ import annotations
import abc
import asyncio
from collections.abc import Iterable, Mapping
import copy
from dataclasses import dataclass
import logging
from types import MappingProxyType
@ -443,6 +444,34 @@ class FlowHandler:
"""If we should show advanced options."""
return self.context.get("show_advanced_options", False)
def add_suggested_values_to_schema(
self, data_schema: vol.Schema, suggested_values: Mapping[str, Any]
) -> vol.Schema:
"""Make a copy of the schema, populated with suggested values.
For each schema marker matching items in `suggested_values`,
the `suggested_value` will be set. The existing `suggested_value` will
be left untouched if there is no matching item.
"""
schema = {}
for key, val in data_schema.schema.items():
if isinstance(key, vol.Marker):
# Exclude advanced field
if (
key.description
and key.description.get("advanced")
and not self.show_advanced_options
):
continue
new_key = key
if key in suggested_values and isinstance(key, vol.Marker):
# Copy the marker to not modify the flow schema
new_key = copy.copy(key)
new_key.description = {"suggested_value": suggested_values[key]}
schema[new_key] = val
return vol.Schema(schema)
@callback
def async_show_form(
self,

View File

@ -210,25 +210,9 @@ class SchemaCommonFlowHandler:
if data_schema.schema:
# Make a copy of the schema with suggested values set to saved options
schema = {}
for key, val in data_schema.schema.items():
if isinstance(key, vol.Marker):
# Exclude advanced field
if (
key.description
and key.description.get("advanced")
and not self._handler.show_advanced_options
):
continue
new_key = key
if key in suggested_values and isinstance(key, vol.Marker):
# Copy the marker to not modify the flow schema
new_key = copy.copy(key)
new_key.description = {"suggested_value": suggested_values[key]}
schema[new_key] = val
data_schema = vol.Schema(schema)
data_schema = self._handler.add_suggested_values_to_schema(
data_schema, suggested_values
)
errors = {"base": str(error)} if error else None