forms

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ActionGroup             = "forms"
	ActionSubmissionsDelete = "forms.submissions_delete"
)

The forms' actions in the action log: their group and types. A form created, published, deleted… is the core's "Content" group (modulekit.RecordNodeCreated, RecordNodeSaved, the core's deletion).

View Source
const ConsentValue = "1"

ConsentValue - the stored value of a ticked consent element.

View Source
const WebformSubmissionsPerPage = 50

WebformSubmissionsPerPage - submissions per page of the list.

Variables

View Source
var (
	ErrWebformClosed        = i18n.Errorf("The form is closed.")
	ErrWebformUnavailable   = i18n.Errorf("The form is not available.")
	ErrWebformLoginRequired = i18n.Errorf("Log in to fill in the form.")
	ErrWebformAlreadySent   = i18n.Errorf("You have already sent this form.")
)

Why a form takes no submission now.

View Source
var Assets embed.FS

Assets - the module's templates/ and static/, built into the binary (modules.Assets, paths.SetModuleAssets): a site runs without the module's source directory.

View Source
var WebformDefaultFileExtensions = []string{"pdf", "doc", "docx", "odt", "rtf", "txt", "xls", "xlsx", "ods", "jpg", "jpeg", "png", "gif", "webp"}

WebformDefaultFileExtensions - the extensions a file element allows when it lists none: documents and pictures.

WebformElementTypes - the element types, in the editor's order.

Functions

func CleanWebformSource

func CleanWebformSource(raw string, hosts ...string) string

CleanWebformSource - raw (a path, or an address of one of hosts) as the path of the site's page a submission came from: "/…" with its query, no fragment; "" - not a page of this site, or too long.

func ParseWebformFileValue

func ParseWebformFileValue(v string) (path, name string)

ParseWebformFileValue - the path and the original name of a stored file value.

func ParseWebformNumber

func ParseWebformNumber(v string) (float64, bool)

ParseWebformNumber - a number as typed ("1,5" too); ok false for anything else (or not finite).

func ParseWebformOptions

func ParseWebformOptions(text string) []string

ParseWebformOptions - the non-empty trimmed lines of text.

func RegisterWebformRoutes

func RegisterWebformRoutes(r modulekit.Mux, store *sessions.CookieStore, wc *WebformController, submitRL *ratelimit.RateLimiter)

RegisterWebformRoutes registers a form's submission (the forms module), open to anonymous visitors and rate limited.

func ValidateWebformInput

func ValidateWebformInput(elements WebformElements, input map[int][]string) (map[int][]string, map[int]string)

ValidateWebformInput - the cleaned values of the elements (trimmed, empty dropped) and the errors by element ID (untranslated sources): required, e-mail format, a choice among the options, one value for a single-value element, a length limit.

func WebformFileValue

func WebformFileValue(path, name string) string

WebformFileValue - the stored value of a sent file: its path in the private files directory and its original name.

func WebformNotification

func WebformNotification(w Webform, values map[int][]string, source string) (subject, body string)

WebformNotification - the e-mail about a submission, in the site's language: the form's title, every answered element as "Label: value" (several values joined by ", "), the page it was sent from (source; "" - unknown) and the link to its submissions.

func Wire

func Wire(d modulekit.Deps) modulekit.Parts

Wire - forms, their elements and submissions: the service (a submission notifies the form's addresses by e-mail; files sent with forms go to the private directory, within the upload policy's size limit, and leave with their form), its actions in the action log, the "Form" block's choices and [[form:<id>]] in texts, the controller (the form content type's pages) and routes (modulekit).

Types

type EntWebformRepository

type EntWebformRepository struct {
	// contains filtered or unexported fields
}

EntWebformRepository implements WebformRepository on the module's own tables; a form's node (the core's NodesRepository), row and elements are written in one transaction (modulekit.InTx). A form's node and a submission's author are the core's rows, read through its repositories.

func NewWebformRepository

func NewWebformRepository(db *sql.DB, nodes modulekit.NodesRepository, users modulekit.UserRepository) *EntWebformRepository

NewWebformRepository creates a EntWebformRepository.

func (*EntWebformRepository) AddSubmission

func (r *EntWebformRepository) AddSubmission(ctx context.Context, s WebformSubmission) (int, error)

AddSubmission - see WebformRepository.AddSubmission.

func (*EntWebformRepository) AnswerCounts

func (r *EntWebformRepository) AnswerCounts(ctx context.Context, elementIDs, choiceIDs []int) (WebformAnswerCounts, error)

AnswerCounts - see WebformRepository.AnswerCounts.

func (*EntWebformRepository) ByNodeID

func (r *EntWebformRepository) ByNodeID(ctx context.Context, nodeID int) (*Webform, error)

ByNodeID - the form of node nodeID, with its elements, its node and the node's SEO.

func (*EntWebformRepository) BySlug

func (r *EntWebformRepository) BySlug(ctx context.Context, slug string) (*Webform, error)

BySlug - the form whose node has slug (ErrEntityNotFound - none, or a node of another type).

func (*EntWebformRepository) CountSubmissions

func (r *EntWebformRepository) CountSubmissions(ctx context.Context, webformID int) (int, error)

CountSubmissions - see WebformRepository.CountSubmissions.

func (*EntWebformRepository) Create

func (r *EntWebformRepository) Create(ctx context.Context, w Webform) (int, error)

Create - see WebformRepository.Create.

func (*EntWebformRepository) DeleteSubmissions

func (r *EntWebformRepository) DeleteSubmissions(ctx context.Context, webformID int, ids []int) (int, error)

DeleteSubmissions - see WebformRepository.DeleteSubmissions.

func (*EntWebformRepository) HasUserSubmission

func (r *EntWebformRepository) HasUserSubmission(ctx context.Context, webformID, userID int) (bool, error)

HasUserSubmission - see WebformRepository.HasUserSubmission.

func (*EntWebformRepository) List

func (r *EntWebformRepository) List(ctx context.Context) ([]Webform, error)

List - see WebformRepository.List.

func (*EntWebformRepository) Submission

func (r *EntWebformRepository) Submission(ctx context.Context, webformID, id int) (*WebformSubmission, error)

Submission - see WebformRepository.Submission.

func (*EntWebformRepository) SubmissionIDsBefore

func (r *EntWebformRepository) SubmissionIDsBefore(ctx context.Context, webformID int, t time.Time) ([]int, error)

SubmissionIDsBefore - see WebformRepository.SubmissionIDsBefore.

func (*EntWebformRepository) SubmissionNeighbors

func (r *EntWebformRepository) SubmissionNeighbors(ctx context.Context, s WebformSubmission) (newer, older int, err error)

SubmissionNeighbors - see WebformRepository.SubmissionNeighbors.

func (*EntWebformRepository) SubmissionStats

func (r *EntWebformRepository) SubmissionStats(ctx context.Context) (map[int]WebformStats, error)

SubmissionStats - see WebformRepository.SubmissionStats.

func (*EntWebformRepository) SubmissionValue

func (r *EntWebformRepository) SubmissionValue(ctx context.Context, webformID, submissionID, elementID, delta int) (string, error)

SubmissionValue - see WebformRepository.SubmissionValue.

func (*EntWebformRepository) SubmissionValues

func (r *EntWebformRepository) SubmissionValues(ctx context.Context, submissionIDs, elementIDs []int) ([]string, error)

SubmissionValues - see WebformRepository.SubmissionValues.

func (*EntWebformRepository) Submissions

func (r *EntWebformRepository) Submissions(ctx context.Context, webformID, limit, offset int) ([]WebformSubmission, error)

Submissions - see WebformRepository.Submissions.

func (*EntWebformRepository) Update

func (r *EntWebformRepository) Update(ctx context.Context, w Webform) error

Update - see WebformRepository.Update.

type Webform

type Webform struct {
	ID   int
	Node modulekit.Node
	// Description - the text above the form (plain text).
	Description string
	// Confirmation - the message after a submission (plain text; "" -
	// the default one).
	Confirmation string
	// ConfirmationURL - the site path a submission leads to instead of
	// the message ("" - the message).
	ConfirmationURL string
	// SubmitLabel - the submit button's text ("" - the default).
	SubmitLabel string
	// Closed - the form takes no submissions.
	Closed bool
	// NotifyEmail - addresses told about every submission, comma
	// separated ("" - nobody).
	NotifyEmail string
	// LimitPerUser - one submission per signed-in user; visitors sign in
	// to send it.
	LimitPerUser bool
	// MaxSubmissions - the form closes after this many (0 - no limit).
	MaxSubmissions int
	// ClosesAt - the form closes at this time (nil - never).
	ClosesAt *time.Time
	Elements WebformElements
}

Webform - a form of the forms module: a node of type "form" (title, address, SEO, comments) with its own elements.

func ToWebformEntity

func ToWebformEntity(w *generated.Webform) *Webform

ToWebformEntity maps a form with its elements (ordered by weight); its node is the core's (the repository adds it).

func (Webform) ElementIDByName

func (w Webform) ElementIDByName(name string) int

ElementIDByName - the ID of the element with this machine name (0 - none).

func (Webform) HasFileElement

func (w Webform) HasFileElement() bool

HasFileElement - whether the form sends files (a multipart form).

func (Webform) NotifyAddresses

func (w Webform) NotifyAddresses() []string

NotifyAddresses - NotifyEmail's addresses, trimmed, empty ones dropped.

type WebformAnalysis

type WebformAnalysis struct {
	Total    int
	Elements []WebformElementAnalysis
}

WebformAnalysis - a form's answers summed up (its Analysis page).

type WebformAnswerCounts

type WebformAnswerCounts struct {
	// Answered - element ID → submissions with an answer.
	Answered map[int]int
	// Values - choice element ID → value → times chosen.
	Values map[int]map[string]int
}

WebformAnswerCounts - a form's answers counted (the analysis page).

type WebformController

type WebformController struct {
	*modulekit.BaseController
	// contains filtered or unexported fields
}

WebformController - the forms module's pages: a form (node of type "form") is created, edited and deleted like other content, shown at its address and submitted there.

func NewWebformController

func NewWebformController(base *modulekit.BaseController, webforms *WebformService, nodes modulekit.NodesService, nodeDeleter modulekit.NodeDeleter) *WebformController

NewWebformController creates a WebformController on base.

func (*WebformController) Analysis

func (c *WebformController) Analysis(w http.ResponseWriter, r *http.Request)

Analysis handles GET /node/{id}/form/analysis: the form's answers summed up - per question those who answered, per choice each option's count.

func (*WebformController) Create

Create handles POST /create/form.

func (*WebformController) CreateForm

func (c *WebformController) CreateForm(w http.ResponseWriter, r *http.Request)

CreateForm handles GET /create/form.

func (*WebformController) Delete

Delete handles POST /node/{id}/delete for a form: its submissions go with it.

func (*WebformController) DeleteForm

func (c *WebformController) DeleteForm(w http.ResponseWriter, r *http.Request)

DeleteForm handles POST /admin/forms/{id}/delete: the form goes with its submissions and files (the regular content delete); back to the list.

func (*WebformController) DeleteFormConfirm

func (c *WebformController) DeleteFormConfirm(w http.ResponseWriter, r *http.Request)

DeleteFormConfirm handles GET /admin/forms/{id}/delete: whether to delete the form with its submissions.

func (*WebformController) DeleteSubmissions

func (c *WebformController) DeleteSubmissions(w http.ResponseWriter, r *http.Request)

DeleteSubmissions handles POST /node/{id}/form/submissions/delete: the checked submissions (ids), or the one a row's button names (only), for those who may delete them; back to the list with how many went.

func (*WebformController) Detail

Detail handles a form's page (GET /<slug>): the form, or the confirmation after a submission (?sent=1).

func (*WebformController) Edit

Edit handles GET /node/{id}/edit for a form.

func (*WebformController) Embed

Embed handles GET /node/{id}/form/embed: the form alone (webform_form, no page around it) for the "Form" block, which loads it into any page; forms.js sends it and shows the answer in its place (Submit). Not cached: what it shows depends on the visitor.

func (*WebformController) File

File handles GET /node/{id}/form/file?sid=&eid=&d=: a file sent with the form, for those who may view its submissions - always as a download (never shown in the browser) under its original name.

func (*WebformController) FormPreview

func (c *WebformController) FormPreview(w http.ResponseWriter, r *http.Request)

FormPreview handles POST /create/form/preview and POST /node/{id}/edit/preview (modulekit.NodeFormPreviewer, the editor's Preview button): the form as its editor would save it, on its page as visitors see it - its questions, their conditions and prefills working - with sending off; nothing saved. What saving would refuse is in the strip over the page.

func (*WebformController) FormsList

func (c *WebformController) FormsList(w http.ResponseWriter, r *http.Request)

FormsList handles GET /admin/forms: every form with its submissions count and last time, links to its submissions, CSV and editor, and a delete button for a form the user may delete - for those who may view submissions.

func (*WebformController) PurgeSubmissions

func (c *WebformController) PurgeSubmissions(w http.ResponseWriter, r *http.Request)

PurgeSubmissions handles POST /node/{id}/form/submissions/purge: deletes the form's submissions older than the given days (with their files) - for those who may delete submissions.

func (*WebformController) Save

Save handles POST /node/{id}/edit for a form.

func (*WebformController) Submission

func (c *WebformController) Submission(w http.ResponseWriter, r *http.Request)

Submission handles GET /node/{id}/form/submissions/{sid}: one submission - every question with its answer, the sender, links to the newer and older ones and deleting it.

func (*WebformController) Submissions

func (c *WebformController) Submissions(w http.ResponseWriter, r *http.Request)

Submissions handles GET /node/{id}/form/submissions: the form's submissions, newest first, a page at a time, with the CSV export.

func (*WebformController) SubmissionsCSV

func (c *WebformController) SubmissionsCSV(w http.ResponseWriter, r *http.Request)

SubmissionsCSV handles GET /node/{id}/form/submissions.csv: every submission as CSV (UTF-8 with a BOM for spreadsheet programs): number, date, sender, IP, then a column per element (several values joined by "; ").

func (*WebformController) Submit

Submit handles POST /node/{id}/form: the values (element_<id>, several for checkboxes) are checked and stored, then the page shows the confirmation; a field error or a failed CAPTCHA shows the form again with what was entered. To forms.js (sentByScript) - the form's part in place of the page: the form again (422) or the confirmation; with a page after sending, its address in X-Webform-Redirect.

type WebformElement

type WebformElement struct {
	ID int
	// MachineName - the element's key (exports, e-mails), unique in its
	// form and kept when the label changes.
	MachineName string
	Type        WebformElementType
	Label       string
	Description string
	Required    bool
	// Options - the choices of a select/radios/checkboxes element.
	Options []string
	Weight  int
	// VisibleIfElement / VisibleIfValue - shown only when the earlier
	// element with this machine name has this value ("" - any value);
	// VisibleIfElement "" - always shown.
	VisibleIfElement string
	VisibleIfValue   string
	// VisibleIfRef - the editor's reference to that element: its position
	// in the list plus one (0 - none); the service turns it into
	// VisibleIfElement once machine names are assigned.
	VisibleIfRef int
	// PrefillParam - the address's query parameter whose value fills the
	// element when the form opens ("" - none; forms.js fills it, the
	// server validates the answer as any other).
	PrefillParam string
}

WebformElement - one element (question) of a form.

func (e WebformElement) ConsentLink() string

ConsentLink - a consent element's link to its policy ("" - none).

func (WebformElement) FileExtensions

func (e WebformElement) FileExtensions() []string

FileExtensions - a file element's allowed extensions (lowercase, no dot): its Options, else WebformDefaultFileExtensions.

func (WebformElement) FileName

func (e WebformElement) FileName(v string) string

FileName - a file element's value as shown: the sent file's original name (other elements: the value).

func (WebformElement) FileTypes

func (e WebformElement) FileTypes() string

FileTypes - the allowed extensions as the file input's accept and the hint show them: ".pdf, .docx".

func (WebformElement) NumberMax

func (e WebformElement) NumberMax() string

NumberMax - the highest of NumberRange (for templates).

func (WebformElement) NumberMin

func (e WebformElement) NumberMin() string

NumberMin / NumberMax - NumberRange's parts (for templates).

func (WebformElement) NumberRange

func (e WebformElement) NumberRange() (lowest, highest string)

NumberRange - a number element's limits as stored ("" - none).

func (WebformElement) OptionsText

func (e WebformElement) OptionsText() string

OptionsText - Options one per line (the editor's textarea).

type WebformElementAnalysis

type WebformElementAnalysis struct {
	Element  WebformElement
	Answered int
	Percent  int
	Options  []WebformOptionCount
}

WebformElementAnalysis - one element: how many answered it (of Total) and, for a choice, each option's count (of those who answered).

type WebformElementInput

type WebformElementInput struct {
	// Key - the row's key in the request: the element ID, or "new…" for
	// a row added in the editor.
	Key         string
	ID          int
	Type        WebformElementType
	Label       string
	Description string
	Required    bool
	// Options - one per line.
	Options string
	// Link - a consent element's policy link.
	Link string
	// Ext - a file element's allowed extensions, as typed ("pdf, docx").
	Ext string
	// Min / Max - a number element's limits, as typed ("" - none).
	Min, Max string
	// IfKey / IfValue - shown only when the earlier row with this key has
	// this value ("" key - always).
	IfKey   string
	IfValue string
	// Prefill - the address's query parameter that fills the element ("" -
	// none).
	Prefill string
}

WebformElementInput - one element row of the form editor.

type WebformElementType

type WebformElementType string

WebformElementType - what an element asks for.

const (
	WebformText       WebformElementType = "text"
	WebformTextarea   WebformElementType = "textarea"
	WebformEmail      WebformElementType = "email"
	WebformSelect     WebformElementType = "select"
	WebformRadios     WebformElementType = "radios"
	WebformCheckboxes WebformElementType = "checkboxes"
	// WebformConsent - a checkbox the sender must tick (consent to the
	// processing of personal data), with an optional link to the policy.
	WebformConsent WebformElementType = "consent"
	// WebformFile - a file sent with the form, kept in the private files
	// directory and given only to those who may view submissions; its
	// Options are the allowed extensions.
	WebformFile WebformElementType = "file"
	// WebformNumber - a number; its Options are the limits, "min=<n>" and
	// "max=<n>" (each optional).
	WebformNumber WebformElementType = "number"
	// WebformDate - a date (YYYY-MM-DD).
	WebformDate WebformElementType = "date"
	// WebformPhone - a phone number.
	WebformPhone WebformElementType = "tel"
)

The element types (WebformElement.Type): a line of text, a longer text, an e-mail address, one choice from a list or of radio buttons, any of several checkboxes, and the ones described below.

func (WebformElementType) CanPrefill

func (t WebformElementType) CanPrefill() bool

CanPrefill - the element type can be filled from the address (not a file, not a consent).

func (WebformElementType) HasOptions

func (t WebformElementType) HasOptions() bool

HasOptions - the element is a choice among its Options.

func (WebformElementType) InputType

func (t WebformElementType) InputType() string

InputType - the HTML input type of a one-line element.

func (WebformElementType) Label

func (t WebformElementType) Label() string

Label - the type's name in the editor (a translation source).

func (WebformElementType) Multiple

func (t WebformElementType) Multiple() bool

Multiple - the element takes several values (one per checked choice).

func (WebformElementType) Valid

func (t WebformElementType) Valid() bool

Valid - a known element type.

type WebformElements

type WebformElements []WebformElement

WebformElements - a form's elements, in their order (Webform.Elements).

func (WebformElements) Visible

func (els WebformElements) Visible(values map[int][]string) map[int]bool

Visible - which elements are shown for these values (by element ID): an element with a condition is shown when the earlier element it names is shown and has the value (any value when VisibleIfValue is empty); a condition naming no earlier element never hides.

type WebformFileStore

type WebformFileStore struct {
	// Files - the private files' store.
	Files func() filestore.Store
}

WebformFileStore keeps the files sent with forms in the private files' store (modulekit.PrivateFiles, never served as it is): webform/<node id>/<element id>/<random>.<ext>. Paths it takes back are checked to stay under webform/.

func (WebformFileStore) Open

Open opens a stored file.

func (WebformFileStore) Remove

func (st WebformFileStore) Remove(ctx context.Context, rel string) error

Remove deletes a stored file (a missing one is no error).

func (WebformFileStore) RemoveAll

func (st WebformFileStore) RemoveAll(ctx context.Context, nodeID, elementID int) error

RemoveAll deletes the files of a form's element, or of the whole form when elementID is 0.

func (WebformFileStore) Save

func (st WebformFileStore) Save(ctx context.Context, nodeID, elementID int, ext string, data []byte) (string, error)

Save writes data as a new file of the form's element; returns its path relative to the private files.

type WebformForm

type WebformForm struct {
	modulekit.NodeMetaFields
	NodeID       int
	Title        string
	Slug         string
	Description  string
	Confirmation string
	// ConfirmationURL - the path a submission leads to ("" - the message).
	ConfirmationURL string
	SubmitLabel     string
	Closed          bool
	NotifyEmail     string
	LimitPerUser    bool
	// MaxSubmissions - as typed ("" - no limit).
	MaxSubmissions string
	// ClosesAt - datetime-local in the site's zone ("" - never).
	ClosesAt     string
	Status       int
	OnModeration int
	CommentMode  string
	Elements     []WebformElementInput
}

WebformForm - the create/edit form of a form (node/edit_webform.html). Element rows are posted as element_row (their keys, in order) and element_<field>_<key>, so an unchecked "required" box can't shift rows.

func WebformFormFromEntity

func WebformFormFromEntity(w *Webform, loc *time.Location) *WebformForm

WebformFormFromEntity - the editor's fields of a stored form (dates in loc, the site's zone).

func (*WebformForm) Limits

func (f *WebformForm) Limits(loc *time.Location) (maxSubmissions int, closesAt *time.Time)

Limits - the form's limits of the editor's fields (after Validate): the submission limit and the closing time read in loc, the site's zone.

func (*WebformForm) ParseWebformForm

func (f *WebformForm) ParseWebformForm(r *http.Request)

ParseWebformForm reads the editor's fields.

func (*WebformForm) Validate

func (f *WebformForm) Validate(ctx context.Context) map[string]string

Validate - errors by field ("title", "elements", "element_<key>").

func (*WebformForm) WebformElements

func (f *WebformForm) WebformElements() WebformElements

WebformElements - the form's elements of the editor's rows (machine names of existing ones are kept by the repository).

type WebformListItem

type WebformListItem struct {
	Webform Webform
	WebformStats
}

WebformListItem - a form in the admin list.

type WebformOptionCount

type WebformOptionCount struct {
	Value   string
	Count   int
	Percent int
	Other   bool
}

WebformOptionCount - an option's count; Other - a value no longer among the options (changed since it was sent).

type WebformRepository

type WebformRepository interface {
	ByNodeID(ctx context.Context, nodeID int) (*Webform, error)
	BySlug(ctx context.Context, slug string) (*Webform, error)
	// Create stores the form's node, form row and elements; returns the
	// node ID.
	Create(ctx context.Context, w Webform) (int, error)
	// Update stores the node, the form row and the elements: new ones are
	// added, changed ones updated, missing ones deleted with their values.
	Update(ctx context.Context, w Webform) error
	// AddSubmission stores a submission with its values; returns its ID.
	AddSubmission(ctx context.Context, s WebformSubmission) (int, error)
	// List - every form (node ID and title in Node), by title.
	List(ctx context.Context) ([]Webform, error)
	// SubmissionStats - per form ID: its submissions and the last one's
	// time (forms without any are absent).
	SubmissionStats(ctx context.Context) (map[int]WebformStats, error)
	// CountSubmissions - the form's submissions.
	CountSubmissions(ctx context.Context, webformID int) (int, error)
	// DeleteSubmissions deletes those of the submissions (IDs) that belong
	// to the form, with their values; returns how many.
	DeleteSubmissions(ctx context.Context, webformID int, ids []int) (int, error)
	// SubmissionValues - the stored values of these elements in these
	// submissions (the files to remove with them).
	SubmissionValues(ctx context.Context, submissionIDs, elementIDs []int) ([]string, error)
	// SubmissionValue - one value of a submission of the form (nil error,
	// "" - none).
	SubmissionValue(ctx context.Context, webformID, submissionID, elementID, delta int) (string, error)
	// AnswerCounts - per element of elementIDs: the submissions with an
	// answer; per element of choiceIDs also each stored value's count.
	AnswerCounts(ctx context.Context, elementIDs, choiceIDs []int) (WebformAnswerCounts, error)
	// SubmissionIDsBefore - the form's submissions sent before t.
	SubmissionIDsBefore(ctx context.Context, webformID int, t time.Time) ([]int, error)
	// Submission - one submission of the form with its values and sender
	// (nil, nil - none).
	Submission(ctx context.Context, webformID, id int) (*WebformSubmission, error)
	// SubmissionNeighbors - the submissions next to s in the list's order
	// (newest first): the newer and the older one (0 - none).
	SubmissionNeighbors(ctx context.Context, s WebformSubmission) (newer, older int, err error)
	// HasUserSubmission - whether the user has sent the form.
	HasUserSubmission(ctx context.Context, webformID, userID int) (bool, error)
	// Submissions - the form's submissions with their values and senders,
	// newest first.
	Submissions(ctx context.Context, webformID, limit, offset int) ([]WebformSubmission, error)
}

WebformRepository - the forms module's storage.

type WebformSender

type WebformSender struct {
	UserID   *int
	RemoteIP string
	Source   string
}

WebformSender - who sent a submission and from where: the signed-in user (nil - anonymous), the address, the site's page (a path, "" - unknown).

type WebformService

type WebformService struct {
	// contains filtered or unexported fields
}

WebformService - the forms module: forms with their elements and their submissions.

func NewWebformService

func NewWebformService(repo WebformRepository, nodes modulekit.NodesService, baseLogger *slog.Logger) *WebformService

NewWebformService creates a WebformService.

func (*WebformService) AdminList

func (s *WebformService) AdminList(ctx context.Context) ([]WebformListItem, error)

AdminList - every form with its submissions count and last time, by title.

func (*WebformService) Analysis

func (s *WebformService) Analysis(ctx context.Context, w Webform) (WebformAnalysis, error)

Analysis counts the form's answers: per element those who answered, per choice element each option (the current ones in order, then other stored values by count).

func (*WebformService) Availability

func (s *WebformService) Availability(ctx context.Context, w Webform, userID *int, now time.Time) error

Availability - why the form takes no submission from the user now (nil - it does): unpublished or on moderation, closed (by hand, by its date or by its submission limit), or one submission per user and the user is anonymous or has sent it.

func (*WebformService) BlockTargets

func (s *WebformService) BlockTargets(ctx context.Context) ([]modulekit.PluginBlockTarget, error)

BlockTargets - the forms the "Form" block can show (its placement page): node ID → title.

func (*WebformService) ByNodeID

func (s *WebformService) ByNodeID(ctx context.Context, nodeID int) (*Webform, error)

ByNodeID - the form of node nodeID, with its elements and its node.

func (*WebformService) BySlug

func (s *WebformService) BySlug(ctx context.Context, slug string) (*Webform, error)

BySlug - the form whose node has slug (ErrEntityNotFound - none).

func (*WebformService) CountSubmissions

func (s *WebformService) CountSubmissions(ctx context.Context, w Webform) (int, error)

CountSubmissions - the form's submissions.

func (*WebformService) Create

func (s *WebformService) Create(ctx context.Context, w Webform) (int, error)

Create stores a new form (a slug from its title when it has none); returns its node ID. The action log gets "Content created".

func (*WebformService) DeleteSubmissions

func (s *WebformService) DeleteSubmissions(ctx context.Context, w Webform, ids []int) (int, error)

DeleteSubmissions deletes the form's submissions with these IDs (IDs of other forms are ignored); returns how many were deleted.

func (*WebformService) EachSubmission

func (s *WebformService) EachSubmission(ctx context.Context, w Webform, fn func(WebformSubmission) error) error

EachSubmission calls fn for every submission of the form, newest first, reading them in batches (the CSV export).

func (*WebformService) Files

func (s *WebformService) Files() *WebformFileStore

Files - the store of sent files (nil - none).

func (*WebformService) OpenSubmissionFile

func (s *WebformService) OpenSubmissionFile(ctx context.Context, w Webform, submissionID, elementID, delta int) (filestore.File, filestore.Info, string, error)

OpenSubmissionFile opens a file sent with the form (submission, element, delta); returns it with its original name.

func (*WebformService) PurgeSubmissions

func (s *WebformService) PurgeSubmissions(ctx context.Context, w Webform, days int, now time.Time) (int, error)

PurgeSubmissions deletes the form's submissions older than days (and their files); returns how many.

func (*WebformService) SetFileStore

func (s *WebformService) SetFileStore(st *WebformFileStore)

SetFileStore gives the forms where to keep the files sent with them.

func (*WebformService) SetNotifier

func (s *WebformService) SetNotifier(send func(to, subject, body string) error)

SetNotifier makes a submission send an e-mail to the form's notify addresses (MailService.SendPlain).

func (*WebformService) SetUploadLimit

func (s *WebformService) SetUploadLimit(limit func(ctx context.Context) int64)

SetUploadLimit sets how the largest sent file is found (the site's upload policy).

func (*WebformService) Stats

Stats - the submissions count and last time of w.

func (*WebformService) Submission

func (s *WebformService) Submission(ctx context.Context, w Webform, id int) (sub *WebformSubmission, newer, older int, err error)

Submission - one submission of the form with the newer and older ones' IDs (0 - none); nil when the form has no such submission.

func (*WebformService) Submissions

func (s *WebformService) Submissions(ctx context.Context, w Webform, page int) ([]WebformSubmission, error)

Submissions - a page (from 1) of the form's submissions, newest first.

func (*WebformService) Submit

func (s *WebformService) Submit(ctx context.Context, w Webform, input map[int][]string, uploads map[int]WebformUpload, from WebformSender) (map[int]string, error)

Submit validates the values (by element ID; one per checked choice of a checkboxes element) and stores the submission. Field errors (by element ID, untranslated sources) come back with a nil error; a form that takes no submission from the user gives Availability's error. The sender's page (from) is kept with it and named in the notification.

func (*WebformService) Update

func (s *WebformService) Update(ctx context.Context, w Webform) error

Update stores the form; existing elements keep their machine names, new ones get names unique among them. What it changed of the content (status, author, address) goes to the action log.

func (*WebformService) UploadLimit

func (s *WebformService) UploadLimit(ctx context.Context) int64

UploadLimit - the largest file a form takes, in bytes.

type WebformStats

type WebformStats struct {
	Count int
	Last  time.Time
}

WebformStats - a form's submissions at a glance (the admin list).

type WebformSubmission

type WebformSubmission struct {
	ID        int
	WebformID int
	// UserID - the signed-in sender, nil - anonymous.
	UserID *int
	// Username, UserSlug - the sender's, when listed ("" - anonymous or
	// deleted).
	Username string
	UserSlug string
	RemoteIP string
	// SourceURL - the site's page (a path) the form was sent from: the
	// page it's embedded in, or the one linking to its own page ("" -
	// unknown).
	SourceURL string
	CreatedAt time.Time
	Values    map[int][]string
}

WebformSubmission - one sent form: values by element ID (a checkboxes element has one per checked choice).

type WebformUpload

type WebformUpload struct {
	Name string
	Data []byte
}

WebformUpload - a file sent for a file element.

Directories

Path Synopsis
ent
Package ent - the forms module's own ent schema (schema/), its generated client (generated/, go generate) and migration files (migrations/<dialect>/, scripts/migrations_gen.sh writes them), apart from the core's: the module's set of migrations (Schema).
Package ent - the forms module's own ent schema (schema/), its generated client (generated/, go generate) and migration files (migrations/<dialect>/, scripts/migrations_gen.sh writes them), apart from the core's: the module's set of migrations (Schema).
schema
Package schema - the forms module's ent schema, apart from the core's.
Package schema - the forms module's ent schema, apart from the core's.
Package manifest declares the forms module (its registry entry): a "form" content type whose items have their own elements and collect submissions.
Package manifest declares the forms module (its registry entry): a "form" content type whose items have their own elements and collect submissions.

Jump to

Keyboard shortcuts

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