modeladmin

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 15, 2026 License: EUPL-1.2 Imports: 23 Imported by: 0

Documentation

Overview

Package modeladmin provides a generic, Django-style ModelAdmin for auto-generating CRUD admin views from Bun models.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ColumnValue

func ColumnValue(item any, field string) template.HTML

ColumnValue extracts a display value for a list column from an item.

func ColumnValueFunc

func ColumnValueFunc(t func(string) string, computed map[string]func(any) template.HTML) func(any, string) template.HTML

ColumnValueFunc returns a columnValue function that uses the given translator and computed column functions.

func FieldValue

func FieldValue(item any, field string) any

FieldValue extracts a field value from a struct by field name. Returns the value as any, or nil if the field is not found.

func RegisterTableDisplayName added in v0.5.0

func RegisterTableDisplayName(table, displayName string)

RegisterTableDisplayName records a table → display name mapping. This is called automatically by Init() for each ModelAdmin, but can also be called manually for tables that don't have their own ModelAdmin (e.g. internal tables like credentials or recovery_codes).

Types

type ActiveChoice

type ActiveChoice struct {
	Value    string
	Label    string
	URL      string // pre-built URL with this filter applied
	IsActive bool
}

ActiveChoice represents a single filter option with its computed URL.

type ActiveFilter

type ActiveFilter struct {
	Field     string
	Label     string
	Choices   []ActiveChoice
	HasActive bool // true if any choice is selected
}

ActiveFilter holds filter state for rendering in the list template.

type BulkAction added in v0.5.0

type BulkAction struct {
	Slug    string // URL segment: /admin/{model}/bulk/{slug}
	Label   string // button text (i18n key)
	Confirm string // JS confirm() text (i18n key); empty = no confirm
	Handler func(ctx context.Context, db *bun.DB, ids []string) error
}

BulkAction defines a bulk operation on multiple selected items.

func DeleteBulkAction added in v0.5.0

func DeleteBulkAction[T any]() BulkAction

DeleteBulkAction returns a BulkAction that deletes selected items by ID.

type CascadeImpact added in v0.5.0

type CascadeImpact struct {
	Table       string // SQL table name
	DisplayName string // human-readable name (from registered ModelAdmin, or Table as fallback)
	Count       int
}

CascadeImpact holds the count of rows that will be cascade-deleted in a child table.

type ChoicesFunc added in v0.3.0

type ChoicesFunc func(ctx context.Context) ([]forms.Choice, error)

ChoicesFunc returns dynamic choices for a select field, typically loaded from the database.

type FilterDef

type FilterDef struct {
	Field    string         // database column name
	Label    string         // human-readable label
	LabelKey string         // i18n key for the label; translated via i18n.T at request time
	Type     string         // "select", "bool", "date_range"
	Choices  []forms.Choice // for select filters
}

FilterDef describes a filter available in the admin list view.

type ItemActions

type ItemActions struct {
	Actions []RenderAction
}

ItemActions holds the actions available for a specific item.

type ModelAdmin

type ModelAdmin[T any] struct {
	// Slug is the URL path segment, e.g. "articles".
	Slug string
	// DisplayName is the singular human-readable name, also used as i18n key, e.g. "Article".
	DisplayName string
	// DisplayPluralName is the plural human-readable name, also used as i18n key, e.g. "Articles".
	DisplayPluralName string
	// DB is the Bun database connection.
	DB *bun.DB
	// Renderer renders list, detail, and form views.
	Renderer Renderer[T]
	// IDFunc extracts the primary key from the request URL.
	// Defaults to chi.URLParam(r, "id").
	IDFunc func(*http.Request) string
	// CanCreate enables the create action. Default: false.
	CanCreate bool
	// CanEdit enables the update action. Default: false.
	CanEdit bool
	// CanDelete enables the delete action. Default: false.
	CanDelete bool
	// ListFields lists struct field names to show in the list view.
	ListFields []string
	// OrderBy is the default ORDER BY clause, e.g. "created_at DESC".
	OrderBy string
	// Relations lists Bun .Relation() names to eager-load.
	Relations []string
	// PageSize is the number of items per page. Default: 25.
	PageSize int
	// SearchFields lists database column names to full-text search across.
	SearchFields []string
	// Filters defines the sidebar filters for the list view.
	Filters []FilterDef
	// SortFields lists database column names that support column sorting.
	SortFields []string
	// RowActions defines custom per-row actions for the list/detail views.
	RowActions []RowAction
	// FieldChoices provides dynamic choices for form select fields.
	// Key is the Go struct field name, value is a function that returns choices
	// (typically loaded from the database). Fields with FieldChoices are
	// rendered as <select> dropdowns instead of text/number inputs.
	FieldChoices map[string]ChoicesFunc
	// EmptyMessage is shown when the list has no items. Default: "No items found."
	EmptyMessage string
	// EmptyMessageKey is the i18n key for the empty-list message.
	// Translated via i18n.T at request time.
	EmptyMessageKey string
	// ReadOnlyFields lists struct field names (by Go name) to render as
	// plain text in forms. Read-only fields cannot be modified by the user;
	// their values are preserved from the model instance.
	ReadOnlyFields []string
	// CanExport enables CSV/JSON export of the list view. Default: false.
	CanExport bool
	// FormOptions holds additional forms.Option[T] applied when building
	// create/edit forms. Use this to pass WithCleanFunc or other options
	// that need external dependencies captured at configuration time.
	FormOptions []forms.Option[T]
	// BulkActions defines bulk operations on multiple selected items.
	BulkActions []BulkAction
	// ListDisplay defines computed columns for the list view.
	// Keys are column names (which can also appear in ListFields).
	// The function receives an item and returns pre-rendered HTML.
	ListDisplay map[string]func(T) template.HTML
	// contains filtered or unexported fields
}

ModelAdmin provides generic CRUD admin views for a Bun model. It is not a burrow.App itself — it's a helper that apps embed to delegate admin route handling.

func (*ModelAdmin[T]) HandleBulkAction added in v0.5.0

func (ma *ModelAdmin[T]) HandleBulkAction(w http.ResponseWriter, r *http.Request) error

HandleBulkAction processes a bulk action on selected items.

func (*ModelAdmin[T]) HandleConfirmDelete added in v0.5.0

func (ma *ModelAdmin[T]) HandleConfirmDelete(w http.ResponseWriter, r *http.Request) error

HandleConfirmDelete renders the delete confirmation page. Exported so apps can mount ModelAdmin confirm-delete views alongside custom handlers.

func (*ModelAdmin[T]) HandleCreate

func (ma *ModelAdmin[T]) HandleCreate(w http.ResponseWriter, r *http.Request) error

HandleCreate processes the create form submission. Exported so apps can mount ModelAdmin create alongside custom handlers.

func (*ModelAdmin[T]) HandleDelete

func (ma *ModelAdmin[T]) HandleDelete(w http.ResponseWriter, r *http.Request) error

HandleDelete deletes an item by ID. Exported so apps can mount ModelAdmin delete alongside custom handlers.

func (*ModelAdmin[T]) HandleDetail

func (ma *ModelAdmin[T]) HandleDetail(w http.ResponseWriter, r *http.Request) error

HandleDetail renders the detail/edit form for an existing item. Exported so apps can mount ModelAdmin detail views alongside custom handlers.

func (*ModelAdmin[T]) HandleExportCSV added in v0.5.0

func (ma *ModelAdmin[T]) HandleExportCSV(w http.ResponseWriter, r *http.Request) error

HandleExportCSV streams the filtered list as a CSV download.

func (*ModelAdmin[T]) HandleExportJSON added in v0.5.0

func (ma *ModelAdmin[T]) HandleExportJSON(w http.ResponseWriter, r *http.Request) error

HandleExportJSON writes the filtered list as a JSON array download.

func (*ModelAdmin[T]) HandleList

func (ma *ModelAdmin[T]) HandleList(w http.ResponseWriter, r *http.Request) error

HandleList renders the paginated list view. Exported so apps can mount ModelAdmin list views alongside custom handlers.

func (*ModelAdmin[T]) HandleNew

func (ma *ModelAdmin[T]) HandleNew(w http.ResponseWriter, r *http.Request) error

HandleNew renders the create form. Exported so apps can mount ModelAdmin form views alongside custom handlers.

func (*ModelAdmin[T]) HandleUpdate

func (ma *ModelAdmin[T]) HandleUpdate(w http.ResponseWriter, r *http.Request) error

HandleUpdate processes the edit form submission. Exported so apps can mount ModelAdmin update alongside custom handlers.

func (*ModelAdmin[T]) Init added in v0.5.0

func (ma *ModelAdmin[T]) Init()

Init runs boot-time detection (FTS5, cascade foreign keys) for this ModelAdmin. Called automatically by Routes(). Call manually when registering routes without Routes().

func (*ModelAdmin[T]) Routes

func (ma *ModelAdmin[T]) Routes(r chi.Router)

Routes mounts all CRUD routes for this ModelAdmin on the given router. Routes are mounted under /{slug} so the caller should mount this within the /admin route group.

type RenderAction

type RenderAction struct {
	Slug    string
	Label   string
	Icon    template.HTML
	Method  string
	Class   string
	Confirm string
}

RenderAction holds action metadata for template rendering (no handler/ShowWhen).

type RenderBulkAction added in v0.5.0

type RenderBulkAction struct {
	Slug    string
	Label   string
	Confirm string
}

RenderBulkAction holds bulk-action metadata for template rendering (no handler).

type RenderConfig

type RenderConfig struct {
	Slug              string
	DisplayName       string
	DisplayPluralName string
	CanCreate         bool
	CanEdit           bool
	CanDelete         bool
	CanExport         bool
	ListFields        []string // Go struct field names (for columnValue/fieldValue lookups)
	ListFieldLabels   []string // translated column headers (parallel to ListFields)
	IDField           string   // struct field name for the primary key (default: "ID")
	Filters           []ActiveFilter
	RowActions        []RenderAction
	HasRowActions     bool
	ItemActionSets    [][]RenderAction // per-item action sets, parallel to items (ShowWhen-evaluated)
	BulkActions       []RenderBulkAction
	HasBulkActions    bool
	EmptyMessage      string
	ComputedColumns   map[string]func(any) template.HTML // field → render function
	DeleteImpacts     []CascadeImpact                    // cascade-delete impact counts (confirm-delete page)
}

RenderConfig holds display metadata passed to the renderer.

type Renderer

type Renderer[T any] interface {
	List(w http.ResponseWriter, r *http.Request, items []T, page burrow.PageResult, cfg RenderConfig) error
	Detail(w http.ResponseWriter, r *http.Request, item *T, cfg RenderConfig) error
	Form(w http.ResponseWriter, r *http.Request, item *T, fields []forms.BoundField, cfg RenderConfig) error
	ConfirmDelete(w http.ResponseWriter, r *http.Request, item *T, cfg RenderConfig) error
}

Renderer defines how ModelAdmin views are rendered.

type RowAction

type RowAction struct {
	Slug     string              // URL segment: /admin/{model}/{id}/{slug}
	Label    string              // button text
	Icon     template.HTML       // icon HTML (optional)
	Method   string              // "POST" or "DELETE" (default: "POST")
	Class    string              // CSS class (default: "btn-outline-secondary")
	Confirm  string              // hx-confirm text (empty = no confirm)
	Handler  burrow.HandlerFunc  // the actual handler
	ShowWhen func(item any) bool // nil = always show
}

RowAction defines a custom per-row action in the admin list/detail views.

Directories

Path Synopsis
Package templates provides the default HTML template renderer for modeladmin CRUD views.
Package templates provides the default HTML template renderer for modeladmin CRUD views.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL