In Databricks notebooks, dbutils.widgets
provide a way to create interactive controls like dropdowns, text inputs, and multi-selects. These widgets make your notebooks more interactive by allowing users to input parameters that can drive the notebook’s behavior without editing the code itself.
Types of Widgets
- Text Box (
dbutils.widgets.text
): Allows users to input free-form text. - Dropdown (
dbutils.widgets.dropdown
): Presents a dropdown menu with predefined options. - Combobox (
dbutils.widgets.combobox
): A combination of a text box and a dropdown, allowing users to either select from a list or enter a new value. - Multi-Select (
dbutils.widgets.multiselect
): Allows users to select multiple options from a dropdown list.
Common dbutils.widgets Commands
Create a Text Box
dbutils.widgets.text(“input_text”, “default_value”, “Text Input”)
#SQL
CREATE WIDGET TEXT tableName DEFAULT ‘customers’
- “input_text”: The name of the widget (used to retrieve the value).
- “default_value”: Default value shown when the widget is created.
- “Text Input”: Label shown next to the widget in the notebook UI.
Create a Dropdown
dbutils.widgets.dropdown(“dropdown”, “option1”, [“option1”, “option2”, “option3”], “Dropdown Label”)
#SQL
CREATE WIDGET DROPDOWN country DEFAULT ‘USA’ CHOICES [‘USA’, ‘UK’, ‘India’]
"dropdown"
: The name of the widget."option1"
: Default selected option.["option1", "option2", "option3"]
: List of options."Dropdown Label"
: Label for the dropdown.
Create a Combobox
dbutils.widgets.combobox(“combobox”, “option1”, [“option1”, “option2”, “option3”], “Combobox Label”)
Create a Multi-Select
dbutils.widgets.multiselect(“multi_select”, “option1”, [“option1”, “option2”, “option3”], “Multi-Select Label”)
#SQL
CREATE WIDGET MULTISELECT status DEFAULT ‘active’ CHOICES [‘active’, ‘inactive’, ‘pending’]
Retrieving Widget Values
value = dbutils.widgets.get(“widget_name”)
print(f”Selected value: {value}”)
#SQL
SELECT * FROM ${getArgument(‘tableName’)}
WHERE country = ‘${getArgument(‘country’)}’
AND status IN (${getArgument(‘status’)})
Cation, In sql, use getArgument.
Removing Widgets
Remove a Single Widget
dbutils.widgets.remove(“widget_name”)
#SQL
— Remove widgets when no longer needed
REMOVE WIDGET widget_name
Remove All Widgets
dbutils.widgets.removeAll()
Please do not hesitate to contact me if you have any questions at William . chen @ mainri.ca
(remove all space from the email account 😊)