This repository demonstrates how to implement and use Union Forms in Ash Framework with Phoenix LiveView. Union type in Ash allow you to create fields that can contain different types of data structures.
main: Implementation usingAsh.DataLayer.Etsdata layerpostgres: Implementation usingAshPostgres.DataLayerfor PostgreSQL
Union Forms in Ash Phoenix allow you to:
- Create forms for fields that can contain different types of data
- Switch between different form types dynamically
- Validate and submit different data structures based on the selected type
- lib/my_app/plugin_settings_type.ex: Defines the union type with two possible resource types (PluginOne and PluginTwo)
- lib/my_app/plugins/plugin.ex: The main resource that uses the union type in its settings attribute
- lib/my_app_web/plugin_live/form_component.ex: LiveView component that renders the form and handles type switching
- The form renders with a dropdown to select the plugin type (One or Two)
- When the type changes, the form dynamically updates to show the appropriate fields
- The form manages the internal
_union_typefield to track the selected type - Data is properly validated and submitted according to the selected type
The key aspects of this implementation:
- Union Type Definition: The
PluginSettingsTypecreates a union type with two possible embedded resources - Dynamic Form Switching: The form component uses
AshPhoenix.Form.remove_form/3andAshPhoenix.Form.add_form/3to change types - Type-specific Fields: The form conditionally renders different fields based on the selected type
mix setup
mix phx.server
Open localhost:4000/plugins from your browser to see the working example of Union Form.