Skip to main content
Light Dark System

Button

<et2-button> | Et2Button

Buttons represent actions that are available to the user.

Examples

Label

label is the text on the button.

<et2-button label="Save"></et2-button>

Label as content

The label is really the button’s default slot, so you can write it as content instead. Use this when the text needs markup of its own - an attribute can only carry plain text.

Save everything
<et2-button>Save <b>everything</b></et2-button>

Set one or the other, not both. The label setter writes into the first text node it finds, so a button that has both ends up showing the attribute and keeping any elements around it, which is rarely what was meant.

Image

Use image to put an icon in front of the label. image and noSubmit below both come from ButtonMixin, which every button on this page shares.

<et2-button label="Print" image="printer"></et2-button>
<et2-button label="Approve" image="check"></et2-button>

A button with an image and no label is icon-only, and sized square. If that is all you want, Button Icon is the lighter-weight widget for it.

<et2-button image="printer"></et2-button>

An id matching one of a handful of well-known patterns gets an image (and a colour class) for free, so the buttons at the bottom of a dialog look the same everywhere without anyone setting image. save, apply, cancel, delete, edit, copy, close and add are among them; see default_background_images in ButtonMixin for the full list. Setting image yourself always wins.

Variants

variant comes from Shoelace and picks the button’s colour.

<et2-button label="Default"></et2-button>
<et2-button variant="primary" label="Primary"></et2-button>
<et2-button variant="success" label="Success"></et2-button>
<et2-button variant="neutral" label="Neutral"></et2-button>
<et2-button variant="warning" label="Warning"></et2-button>
<et2-button variant="danger" label="Danger"></et2-button>
<et2-button variant="text" label="Text"></et2-button>

primary is deliberately toned down compared to stock Shoelace, because eTemplate puts it on the first button of every dialog and a wall of blue was too loud.

Size

size is small, medium (the default) or large.

<et2-button size="small" label="Small"></et2-button>
<et2-button size="medium" label="Medium"></et2-button>
<et2-button size="large" label="Large"></et2-button>

Prefix and suffix

Beyond image, the prefix and suffix slots take whatever you put in them.

<et2-button label="Download">
    <sl-icon slot="prefix" name="cloud-download"></sl-icon>
    <sl-icon slot="suffix" name="chevron-right"></sl-icon>
</et2-button>

Submitting

By default clicking a button submits the whole eTemplate to the server, where the button’s id tells your code what was clicked. Nothing needs to be wired up for that; it is what a button is.

<et2-button id="button[save]" label="Save"></et2-button>
if (!empty($content['button']))
{
    switch(key($content['button']))
    {
        case 'save': ... 
    }
}

Set noSubmit for a button that should only run client-side code. Returning false from the onclick handler stops the submit for that one click, which is how a confirmation prompt works.

0
<et2-button id="local-example" noSubmit label="Count clicks"></et2-button>
<span id="local-count">0</span>
<script>
    const button = document.getElementById("local-example");
    const count = document.getElementById("local-count");
    button.addEventListener("click", () => {count.textContent = String(1 + parseInt(count.textContent));});
</script>

Skipping validation

noValidation submits without running client-side validation first. Use it on buttons that take the user somewhere else - a Cancel, or a tab of a wizard - where refusing to leave because a required field further down is still empty would be wrong.

<et2-button id="button[cancel]" noValidation label="Cancel" image="cancel"></et2-button>

Disabled and readonly

A button is an input widget, so disabled does what you expect: the button stays on the page, greyed out, and can be enabled again from javascript. That is worth saying out loud, because on a widget that is not an input - a box, a tab, and among this page’s neighbours et2-button-copy and et2-tag - disabled removes the widget from the page entirely. See Disabled vs Readonly vs Hidden.

readonly on a button means the same thing as disabled - there is no value to show - and is implemented by setting the disabled attribute.

<et2-button label="Normal"></et2-button>
<et2-button label="Disabled" disabled></et2-button>
<et2-button label="Readonly" readonly></et2-button>

Add hideOnReadonly to get the older behaviour, where a readonly button is gone rather than greyed. Both attributes are needed: on its own hideOnReadonly does nothing, since a button that is not readonly has nothing to hide from.

<et2-button label="Still here" readonly></et2-button>
<et2-button label="Not here" readonly hideOnReadonly="true"></et2-button>

Keyboard shortcuts

A button whose id matches save gets Ctrl+S and one matching cancel gets Escape, registered globally while the button is on the page. Nothing to set up - it follows from the id, the same way the default image does.

<et2-button id="button[save]" label="Save"></et2-button>

Slots

Name Description
(default) The button’s label.
prefix A presentational prefix icon or similar element.
suffix A presentational suffix icon or similar element.

Learn more about using slots.

Inherited properties (52)

Et2Widget

Name Description
accesskey Accesskey provides a hint for generating a keyboard shortcut for the current element. The attribute value must consist of a single printable character.
actions Set Actions on the widget Each action is defined as an object: move: { type: “drop”, acceptedTypes: “mail”, icon: “move”, caption: “Move to” onExecute: javascript:mail_move” } This will turn the widget into a drop target for “mail” drag types. When “mail” drag types are dropped, the global function mail_move(egwAction action, egwActionObject sender) will be called. The ID of the dragged “mail” will be in sender.id, some information about the sender will be in sender.context. The etemplate2 widget involved can typically be found in action.parent.data.widget, so your handler can operate in the widget context easily. The location varies depending on your action though. It might be action.parent.parent.data.widget To customise how the actions are handled for a particular widget, override _link_actions(). It handles the more widget-specific parts.
align Used by Et2Box to determine alignment. Allowed values are left, right
class CSS Class. This class is applied to the outside, on the web component itself. Due to how WebComponents work, this might not change anything inside the component.
data Set the dataset from a CSV
deferredProperties Any attribute that refers to row content cannot be resolved immediately, but some like booleans cannot stay a string because it’s a boolean attribute. We store them for later, and parse when they’re fully in their row. If you are creating a widget that can go in a nextmatch row, and it has boolean attributes that can change for each row, add those attributes into deferredProperties
disabled Defines whether this widget is visibly disabled. The widget is still visible, but clearly cannot be interacted with. Widgets disabled in the template will not return a value to the application code, even if re-enabled via javascript before submitting. To allow a disabled widget to be re-enabled and return a value, disable via javascript in the app’s et2_ready() instead of an attribute in the template file.
dom_id Get the actual DOM ID, which has been prefixed to make sure it’s unique.
full Take every column of a layout, the same as span="all". Boolean rather than a bare marker so it can be driven from content the way the rest of the template can - full="@is_wide" resolves through the array manager like any other boolean attribute. That does mean it needs a value: write full="true", since an empty full="" resolves to false and removes the attribute again. Reflects for the same reason grow does.
grow How much of a layout’s leftover space this widget should take. Only means anything inside a container that has a layout (see Et2LayoutController): a bare grow or grow="1" takes an equal share of whatever the non-growing children left over, grow="2" takes twice what a grow="1" sibling does. It has to reflect. The layout stylesheet matches the [grow] attribute - CSS cannot see a property - and transformAttributes() only calls setAttribute() for an attribute the element already carries or a property declared as reflecting. Widgets built from a .xet are created with document.createElement() and handed their attributes as an object, so they carry none at that point: without this declaration grow="1" lands as an inert JS property and nothing in the layout ever matches it.
hidden The widget is not visible. As far as the user is concerned, the widget does not exist. Widgets hidden with an attribute in the template may not be created in the DOM, and will not return a value. Widgets can be hidden after creation, and they may return a value if hidden this way.
id Get the ID of the widget
label The label of the widget Legacy support for labels with %s that get wrapped around the widget Not the best way go with webComponents - shouldn’t modify their DOM like this
noLang Disable any translations for the widget
parentId Parent is different than what is specified in the template / hierarchy. Widget ID of another node to insert this node into instead of the normal location
span How many of a layout’s columns this widget should take. span="all" is every column wherever the widget landed, span="end" / span="*" is from its own column to the end of its line. Only means anything inside a container that has a layout, and only for the column layouts - stack gives every child the full width anyway. The same name is also read straight off the XML node by the legacy <grid> widget, for the unrelated job of counting table cells to merge; that path never looks at the widget, so declaring it here does not disturb it. Reflecting it does mean a legacy grid’s span="all" cells now carry the attribute too, which matches nothing outside a layout. Reflects for the same reason grow does.
statustext Tooltip which is shown for this element on hover
styles WebComponent *
options Get property-values as object
supportedWidgetClasses et2_widget compatability

Et2InputWidget

Name Description
autofocus Have browser focus this input on load. Overrides etemplate2.focusOnFirstInput(), use only once per page https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes
hasFeedbackFor Get a list of feedback types
translate List of properties that get translated Done separately to not interfere with properties - if we re-define label property, labels go missing.
needed Compatibility for deprecated name “needed”

SlButton⁠ (Shoelace)

Name Description
caret Draws the button with a caret. Used to indicate that the button triggers a dropdown menu or similar behavior.
circle Draws a circular icon button. When this attribute is present, the button expects a single <sl-icon> in the default slot.
download Tells the browser to download the linked file as this filename. Only used when href is present.
form The “form owner” to associate the button with. If omitted, the closest containing form will be used instead. The value of this attribute must be an id of a form in the same document or shadow root as the button.
formAction Used to override the form owner’s action attribute.
formEnctype Used to override the form owner’s enctype attribute.
formMethod Used to override the form owner’s method attribute.
formNoValidate Used to override the form owner’s novalidate attribute.
formTarget Used to override the form owner’s target attribute.
href When set, the underlying button will be rendered as an <a> with this href instead of a <button>.
loading Draws the button in a loading state.
name The name of the button, submitted as a name/value pair with form data, but only when this button is the submitter. This attribute is ignored when href is present.
outline Draws an outlined button.
pill Draws a pill-style button with rounded edges.
rel When using href, this attribute will map to the underlying link’s rel attribute. Unlike regular links, the default is noreferrer noopener to prevent security exploits. However, if you’re using target to point to a specific tab/window, this will prevent that from working correctly. You can remove or change the default value by setting the attribute to an empty string or a value of your choice, respectively.
size The button’s size.
target Tells the browser where to open the link. Only used when href is present.
type The type of button. Note that the default value is button instead of submit, which is opposite of how native <button> elements behave. When the type is submit, the button will submit the surrounding form.
validationMessage Gets the validation message
validity Gets the validity state object
value The value of the button, submitted as a pair with the button’s name as part of the form data, but only when this button is the submitter. This attribute is ignored when href is present.
variant The button’s theme variant.

ButtonMixin

Name Description
default_background_images images to be used as background-image, if none is explicitly applied and id matches given regular expression
default_classes Classnames added automatically to buttons to set certain hover background colors
hideOnReadonly If button is set to readonly, do we want to hide it completely (old behaviour) or show it as disabled (default) Something’s not quite right here, as the attribute shows up as “hideonreadonly” instead of “hide” but it does not show up without the “attribute”, and attribute:“hideonreadonly” does not show as an attribute
noSubmit Button should submit the etemplate Return false from the click handler to cancel the submit, or set noSubmit to true to skip submitting.
noValidation When submitting, skip the validation step. Allows to submit etemplates directly to the server.

LitElement

Name Description
updateComplete A read-only promise that resolves when the component has finished updating.

Events

Name Description Event Detail
click Missing description MouseEvent
change Missing description Event

Learn more about events.

Inherited methods (40)

SlButton⁠ (Shoelace)

Name Description
blur() Removes focus from the button.
checkValidity() Checks for validity but does not show a validation message. Returns true when valid and false when invalid.
click() Simulates a click on the button.
focus() Sets focus on the button.
getForm() Gets the associated form, if one exists.
reportValidity() Checks for validity and shows the browser’s validation message if the control is invalid.
setCustomValidity() Sets a custom validation message. Pass an empty string to restore validity.

Et2Widget

Name Description
checkCreateNamespace() Checks whether a namespace exists for this element in the content array. If yes, an own perspective of the content array is created. If not, the parent content manager is used. Constructor attributes are passed in case a child needs to make decisions
clone() Creates a copy of this widget.
createElementFromNode() Create a et2_widget from an XML node. First the type and attributes are read from the node. Then the readonly & modifications arrays are checked for changes specific to the loaded data. Then the appropriate constructor is called. After the constructor returns, the widget has a chance to further initialize itself from the XML node when the widget’s loadFromXML() method is called with the node.
getArrayMgr() Returns the array manager object for the given part
getArrayMgrs() Returns an associative array containing the top-most array managers.
getChildren() Get child widgets Use .children to get web component children
getInstanceManager() Returns the instance manager
getPath() Returns the path into the data array. By default, array manager takes care of this, but some extensions need to override this
getRoot() Returns the base widget Usually this is the same as getInstanceManager().widgetContainer
loadFromXML() Loads the widget tree from an XML node
loadingFinished() Needed for legacy compatability.
parseXMLAttrs() The parseXMLAttrs function takes an XML DOM attributes object and adds the given attributes to the _target associative array. This function also parses the legacyOptions. N.B. This is only used for legacy widgets. WebComponents use transformAttributes() and do their own handling of attributes.
set_label() NOT the setter, since we cannot add to the DOM before connectedCallback() TODO: This is not best practice. Should just set property, DOM modification should be done in render https://lit-element.polymer-project.org/guide/templates#design-a-performant-template
setArrayMgr() Sets the array manager for the given part
setArrayMgrs() Sets all array manager objects - this function can be used to set the root array managers of the container object.
setInstanceManager() Set the instance manager Normally this is not needed as it’s set on the top-level container, and we just return that reference
_handleClick() Click handler calling custom handler set via onclick attribute to this.onclick
destroy() et2_widget compatability
set_class() Set the widget class
set_disabled() Wrapper on this.disabled because legacy had it.
set_statustext() supports legacy set_statustext

Et2InputWidget

Name Description
et2HandleBlur() If the value is unchanged, put any held validation messages back Named et2HandleBlur to avoid overwriting handleBlur() in Shoelace components
et2HandleFocus() When input receives focus, clear any validation errors. If the value is the same on blur, we’ll put them back The ones from the server (ManualMessage) can interfere with submitting. Named et2HandleFocus to avoid overwriting handleFocus() in Shoelace components
getInputNode() Reimplemented to pass aria-attributes to button
handleSlChange() Handle sl-change event from Shoelace components and dispatch a change event so anything listening for change events can react to it instead of having to listen for both sl-change and change.
isDirty() Always return false as a button is never dirty
isValid() Used by etemplate2 to determine if we can submit or not
submit() Called whenever the template gets submitted. We return false if the widget is not valid, which cancels the submission.
validate() Massively simplified validate, as compared to what ValidatorMixin gives us, since ValidatorMixin extends FormControlMixin which breaks SlSelect’s render() We take all validators for the widget, and if there’s a value (or field is required) we check the value with each validator. For array values we check each element with each validator. If the value does not pass the validator, we collect the message and display feedback to the user. We handle validation errors from the server with ManualMessages, which always “fail”. If the value is empty, we only validate if the field is required.
_oldChange() Change handler calling custom handler set via onchange attribute

ButtonMixin

Name Description
_get_default_class() Get a default class for the button based on ID
_get_default_image() Get a default image for the button based on ID
_register_default_keyhandler() If button ID has a default keyboard shortcut (eg: Save: Ctrl+S), register with egw_keymanager

These widgets are related by naming but not by inheritance or sub-widget composition.