diff --git a/esphome/components/template/select/__init__.py b/esphome/components/template/select/__init__.py index 574f1f5fb7..08c489a3f3 100644 --- a/esphome/components/template/select/__init__.py +++ b/esphome/components/template/select/__init__.py @@ -87,6 +87,7 @@ async def to_code(config): cg.add(var.set_restore_value(True)) if CONF_SET_ACTION in config: + cg.add_define("USE_TEMPLATE_SELECT_SET_TRIGGER") await automation.build_automation( var.get_set_trigger(), [(cg.StringRef, "x")], config[CONF_SET_ACTION] ) diff --git a/esphome/components/template/select/template_select.cpp b/esphome/components/template/select/template_select.cpp index fa34aa9fa7..2d1f48157f 100644 --- a/esphome/components/template/select/template_select.cpp +++ b/esphome/components/template/select/template_select.cpp @@ -41,7 +41,9 @@ void TemplateSelect::update() { } void TemplateSelect::control(size_t index) { +#ifdef USE_TEMPLATE_SELECT_SET_TRIGGER this->set_trigger_->trigger(StringRef(this->option_at(index))); +#endif if (this->optimistic_) this->publish_state(index); diff --git a/esphome/components/template/select/template_select.h b/esphome/components/template/select/template_select.h index 114d25b9ce..ff5aff7bd3 100644 --- a/esphome/components/template/select/template_select.h +++ b/esphome/components/template/select/template_select.h @@ -18,7 +18,9 @@ class TemplateSelect final : public select::Select, public PollingComponent { void dump_config() override; float get_setup_priority() const override { return setup_priority::HARDWARE; } +#ifdef USE_TEMPLATE_SELECT_SET_TRIGGER Trigger *get_set_trigger() const { return this->set_trigger_; } +#endif void set_optimistic(bool optimistic) { this->optimistic_ = optimistic; } void set_initial_option_index(size_t initial_option_index) { this->initial_option_index_ = initial_option_index; } void set_restore_value(bool restore_value) { this->restore_value_ = restore_value; } @@ -28,7 +30,9 @@ class TemplateSelect final : public select::Select, public PollingComponent { bool optimistic_ = false; size_t initial_option_index_{0}; bool restore_value_ = false; +#ifdef USE_TEMPLATE_SELECT_SET_TRIGGER Trigger *set_trigger_ = new Trigger(); +#endif TemplateLambda f_; ESPPreferenceObject pref_; diff --git a/tests/components/template/common-base.yaml b/tests/components/template/common-base.yaml index 9dc65fbab8..9dece7c3a5 100644 --- a/tests/components/template/common-base.yaml +++ b/tests/components/template/common-base.yaml @@ -296,6 +296,16 @@ select: // Migration guide: Store in std::string std::string stored_option(id(template_select).current_option()); ESP_LOGI("test", "Stored: %s", stored_option.c_str()); + - platform: template + id: template_select_with_action + name: "Template select with action" + options: + - option_a + - option_b + set_action: + - logger.log: + format: "Selected: %s" + args: ["x.c_str()"] lock: - platform: template