Creates and returns a Hublify Datatable-Object.
Functions
Following functions are available for an datatable-instance:
analyzeFields(...)
Analyzes and summarizes fields (columns) of previously set data.
It calculates and caches internally per each field given, following values:
- "sum"
- "min"
- "max"
- "avg"
- "cntNotEmpty" - int Number or data-rows that this value was not null or empty.
- "cntEmpty" - int Number of data-rows where this value was undefined, null or empty (string).
This function is also internally used, when header/footer summary-rows are enabled.
Syntax
analyzeFields(?array $fields): hublify_var_ext_datatable
- $fields
Numerical array of the field-labels (columns) you want to analyze.
cellTplStr(...)
Sets a custom twig-template to format the complete cell-container and values for a given field.
Syntax
cellTplStr(string $field, ?string $tplStr): hublify_var_ext_datatable
- $field
The field to apply this to. - $tplStr
The twig-template string that shall render the container and value for a cell-container.
In this template string you must provide the container-html-elements for this cell, such as "<td>" or similar!
The twig-Template-String gets automatically injected following variables:
- value - mixed The actual raw-data-value
- field - string The field label (= $field)
- row - array The complete data-row as an associative array.
- prevValue - mixed The previous row's field value. Use this e.g. to detect whether this value is same or different than in previous row.
- line - integer The current line number on rendering (1 ... n).
- summary - array Optional summary array for this field. Regard: You have to call function analyzeFields(...) beforehand. Otherwise this summary might not be present or filled!
dataset(...)
Setting the internal dataset-label to which the fields & data belong to.
Benefit of this is that dataTable ...
- ... can automatically translate the table head's field names.
fieldDefinition(...)
Set a field definition for one field.
Syntax
fieldDefinition(string $field, $definition): hublify_var_ext_datatable
$definition can have following properties:
- "type" - string The field-type from Dataset-field-definition.
- "text"
- "
- "sub_type" - string (optional)
- "formatter" - string Can be one of the following. To set one of built-in formatter-functions.
- "number"
Optional formatterParams are:- "fmtType" - string ("si|num") The type of formatting to be applied.
"si" - Scientific Notation. E.g. "5.133" => "5K"
"num" (default) Normal number notation, e.g. "5.133" - - "fmtDecimal" - string (optional, default NULL => "1.0-2") Number of leading digits and fractions.
E.g. "1.0-4" (for up to 4 decimal places)
- "fmtType" - string ("si|num") The type of formatting to be applied.
- "date"
- "datetime"
- "data"
- "text"
- "duration"
- "taskduration"
- "number"
- "formatterParams" - mixed Optiona "formatter"-specific optional parameters.
- "formatterTplLabel" - string (optional)
- "formatterTplStr" - string (optional) Custom Twig-Template-String to render these values.
See function: formatterTplStr(...) for Details. - "sumType" - string (optional, default NULL) What kind of summing to apply on this field (case-insensitive)
- "sum" (NULL) - Summarize Values, using: [sum]
- "avg" - Average of Values, using [avg].
- "cellTplStr" - string (optional)
fieldDefinitions(...)
Sets multiple field definitions at once.
Syntax
fieldDefinitions(array $definitions): hublify_var_ext_datatable
fields(...)
Configures which fields of the data shall be rendered as datatable-columns.
Syntax
fields(array|null $fields) : hublify_var_ext_datatable
- $fields
Numerical array of field-labels to be rendered.
The given order of the fields is regarded on rendering.
NULL resets this filtering setting and resets the rendering all found fields in the data-array.
formatterTpl(...)
Defines a custom twig-template-file to render the values for a given field.
Syntax
formatterTplStr(string $field, ?string $tplFile, ?array $tplParams = null): hublify_var_ext_datatable
- $field
The field to apply this to. - $tplFile
The twig-template-file to be used that shall render the value within the (<td>-) cell-container.
In this template string you must not provide any container-html-elements for this cell, such as "<td>" or similar!
E.g. "@hublify/app/some/path/to/_myFieldFormatter.html.twig"
You can set the formatter-template in two variants:- Full Path: With a starting "@"-character, e.g. "@hublify/hublify/app/components/datatable/formatter/_model-primary.html.twig"
- Shorthand for Standard Hublify Formatter: e.g. "model-primary"
These given shorthand tplFiles are automatically extended to: "@hublify/hublify/app/components/datatable/formatter/_<tplFile>.html.twig"
- Full Path: With a starting "@"-character, e.g. "@hublify/hublify/app/components/datatable/formatter/_model-primary.html.twig"
- $tplParams
Optional array/object of parameters injected into the twig-template as variable "params" for rendering.
The twig-Template-String gets automatically injected following variables:
- value - mixed The actual raw-data-value
- field - string The field label (= $field)
- row - array The complete data-row as an associative array.
- prevValue - mixed The previous row's field value. Use this e.g. to detect whether this value is same or different than in previous row.
- line - integer The current line number on rendering (1 ... n).
- summary - array Optional summary array for this field. Regard: You have to call function analyzeFields(...) beforehand. Otherwise this summary might not be present or filled!
- dataset - string Optionally, the configured "dataset" for this datatable-instance.
- params - array/object Optionally, the configured $tplParams (see above).
Standard Formatter
Currently following standard formatter are available.
"action"
Renders an Hublify-Action-Button for a record: <hfy-action-button...>.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', 'action', { "actionLabel": "<label>", // (required) The action-label of the action to be executed. "dataset": "<dataset>", // (optional) If not given the dataTable's configured "dataset" is used. "primaryKey": "<field>", // (optional) If not given it is detected from the dataset automatically. "actionGroup": "<grp-label>", // (optional, default NULL) The action-group to be used for the action-menu. // If not given, the default action-group "record" will be used. "dspType": "<str>", // (optional, default NULL => "bttn") Determines what should be rendered. Either "bttn" or "icon". "iconLabel": "<str>", // (optional, default NULL) E.g. "hublify/edit". "cssClass": "<str>", // (optional, default NULL) If given, this will be applied to the hfy-icon or the button. // E.g. "btn btn-outline-primary", "btn-link-primary", Icon: "sm app-btn". "bttnText": "<str>", // (optional, default NULL) Manual (override) text for the button. "bttnLayout": "<str>", // (optional, default NULL => "text") What kind of button to render: 'text' | 'ico' | 'ico-text'. "bttnAccess": "<str>", // (optional, default NULL) }) }
"action-menu"
Renders an action-menu for a single record. With the typical "more-horizontal" icon.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "action-menu", { "dataset": "<dataset>", // (optional) If not given the dataTable's configured "dataset" is used. "primaryKey": "<field>", // (optional) If not given it is detected from the dataset automatically. "actionGroup": "<grp-label>", // (optional, default NULL) The action-group to be used for the action-menu. // If not given, the "record" will be used as default. "appendTo": "component", // (optional, default NULL) Set to "component" (default) or "body". }) }
"model-primary"
Renders the cell's content with "<hfy-data-link>"-tag.
The value is then a clickable link with Quick-View enabled.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "model-primary", { "dataset": "<dataset>", // (optional) Override "primaryKey": "<primary-field>", // (optional) Override. Good performance! }) }
"status"
Renders standard Hublify Status-Pill with a <hfy-status>-tag.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "status", { "stateColorField": "<field>", // Field, that contains the color(-hexcode) for the state. "stateIconField": "<field>", // (optional) Field, that contains a possible iconLabel-string. "stateSetLabel": "<str>", // (optional) The state-set-label "stateLogView": true, // (optional) "cssClass": "<str>", // (optional) CSS-Class-String that is set on the <hfy-status>-component. // E.g. "sm", "lg", "xl" "cssStyle": "<str>", // (optional) CSS-Style-String that is set on the <hfy-status>-component. }) }
"active-flag"
Renders a "check-circle" if cell's value is"1"/TRUE or else "circle icon".
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "active-flag") }
"country-flag"
This formatter Renders an Country-Flag-Icon.
The cell's value is expected to be the 2-Letter-ISO-Code for countries (e.g. "DE", "US", "FR", ...) - case-insensitive.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "country-flag") }
"data-view"
Renders a hoverable Hublify-Quick-View-Container with either a standard dataset's view or a custom Twig-Template-File.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "data-view", { "view": "<view-label>", // (optional) "viewTemplate": "<tpl-file>", // (optional) "viewParams": {...}, // (optional) "viewOptions": {...}, // (optional) "text": "<str>", // (optional) A static-text override. }) }
"dyn-reference"
Special formatter to render a dynamic reference to another dataset.
A "dynamic reference" means, that the reference-dataset is not fixed, but can be determined by the actual value of the field. Typically within Hublify-Datasets these fields are named something like:
"...ref_type" -> used as: <dataset>
and
"...ref_id" -> used as: <primary-key-value> // Apply this formatter to this field!
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "dyn-reference", { "refTypeField": "<field>", // (required) The field-label which contains the actual dataset-label. "refIdField": "<field>", // (optional) If given this field is used instead of the one that // this formatter is applied to. "view": "<view-label>", // (optional) "viewTemplate": "<tpl-file>", // (optional) "viewParams": {...}, // (optional) "viewOptions": {...}, // (optional) "text": "<str>", // (optional) A static-text override. }) }
"user"
This formatter is used to display a user's avatar and username.
{# Partial example: #} {{ hublify.dataTable(...) .formatterTpl('<field>', "user") }
formatterTplId(...)
Defines a custom twig-template-file defined by its indexed ID within the Hublify-CMS to render the values for a given field.
Syntax
formatterTplStr(string $field, ?string $tplId, ?array $tplParams = null): hublify_var_ext_datatable
- $field
The field to apply this to. - $tplId
The twig-template's ID that shall render the value within the (<td>-) cell-container.
In this template string you must not provide any container-html-elements for this cell, such as "<td>" or similar! - $tplParams
Optional array/object of parameters injected into the twig-template as variable "params" for rendering.
The twig-Template-String gets automatically injected following variables:
- value - mixed The actual raw-data-value
- field - string The field label (= $field)
- row - array The complete data-row as an associative array.
- prevValue - mixed The previous row's field value. Use this e.g. to detect whether this value is same or different than in previous row.
- line - integer The current line number on rendering (1 ... n).
- summary - array Optional summary array for this field. Regard: You have to call function analyzeFields(...) beforehand. Otherwise this summary might not be present or filled!
- dataset - string Optionally, the configured "dataset" for this datatable-instance.
- params - array/object Optionally, the configured $tplParams (see above).
formatterTplStr(...)
Sets a custom inline twig-template to format the values for a given field.
Syntax
formatterTplStr(string $field, ?string $tplStr, ?array $tplParams = null): hublify_var_ext_datatable
- $field
The field to apply this to. - $tplStr
The twig-template string that shall render the value within the (<td>-) cell-container.
In this template string you must not provide any container-html-elements for this cell, such as "<td>" or similar! - $tplParams
Optional array/object of parameters injected into the twig-template as variable "params" for rendering.
The twig-Template-String gets automatically injected following variables:
- value - mixed The actual raw-data-value
- field - string The field label (= $field)
- row - array The complete data-row as an associative array.
- prevValue - mixed The previous row's field value. Use this e.g. to detect whether this value is same or different than in previous row.
- line - integer The current line number on rendering (1 ... n).
- summary - array Optional summary array for this field. Regard: You have to call function analyzeFields(...) beforehand. Otherwise this summary might not be present or filled!
- dataset - string Optionally, the configured "dataset" for this datatable-instance.
- params - array/object Optionally, the configured $tplParams (see above).
formatValue(...)
Renders a formatted value, defined by its field's (formatter) definition.
This function is primarily used internally.
Syntax
formatValue($value, $field = null): array
Returns
[str] - The formatted value
[align] - "left|center|right"
group(...)
Sets a field for grouping rows.
Syntax
group(string $groupField, array $params = null): hublify_var_ext_datatable
Some informations about group-row-rendering:
- Group rows are always rendered when the group-field's value changes from one row-record to another.
- Group rows can also be formatted / rendered individually with configured formatter-templates.
- Group rows have an automatically set col-span over the whole width of the table.
groups(...)
Sets multiple fields for grouping.
Syntax
function groups(array $groups): hublify_var_ext_datatable
hasField(...)
Returns whether a field currently known within the data.
Syntax
hasField(string $field): bool
setLocale(...)
Sets the locale-string for this dataTable, for later data-formatting.
On dataTable-initialization the render-environment's locale-setting is automatically set.
Syntax
locale(?string $locale): hublify_var_ext_datatable
$locale can be e.g. "de-DE". If NULL localization is disabled.
params(...)
This function can be used to set many datatable-configurations at once.
This can be called multiple times.
Syntax
params(array $params): hublify_var_ext_datatable
Optional keys within $params are:
- [dataset] - string The dataset label. See details in function dataset(...).
- [lineNumbers] - bool
- [lineStart] - int|null (optional, default NULL => 1) The first number of line-numbering.
- [lineNumberColName] - string|null (optional, default NULL => "Nr.") The column-name of the line-numbering column.
- [columnHeaders] - bool|null (optional, default NULL/FALSE) If TRUE, a header-row with the (translated) field-names is shown.
- [headerSticky] - bool|int|null (optional, default NULL/FALSE) If TRUE, for the header-opening row-tag, the css class "hfyDTRowHeader-sticky-top" is applied. Which makes the header-row sticky.
- [sumsHeader] - bool|null (optional, default NULL/FALSE) If TRUE, a header-row with the sums of fields is shown
- [sumsFooter] - bool|null (optional, default NULL/FALSE) If TRUE, a footer-row with the sums of fields is shown
- [fields] - string[] The fields (columns) to render. See details in function fields(...)
- [fieldDefinitions] - string[][] See params-details in function fieldDefinitions(...).
- [groups] - string[][] To enable render grouping. See details in function groups(...)
- [groupSticky] - bool|int|null (optional, default NULL/FALSE) If TRUE, for the opening row-tag, the css class "hfyDTRowGroup-sticky-top" is applied. Which makes the group-row sticky.
- [sorts] - array[] See params-details in function sorts(...).
- [locale] -string|null Sets the localization, e.g. "de-DE". NULL disabled localization.
- [htmlTableClass] - string
- [htmlTableStyle] - string
Optional keys within $params, used for render_csv():
- [csvDelimiter] - string Optional delimiter-string, default: ';'
- [csvEnclosure] - string Optional field-value enclosure-string, default: '"'
- [csvEscape] - string Optional Escape-Character-string, default: '\\'
- [csvEol] - string Optional End-of-Line-string, default: '\n;'
- [csvBom] - boolean If TRUE then preceding BOM-Sequence is written into the resulting string.
render()
Renders the complete datatable into a string.
Syntax
render(): string
render_csv()
Renders the complete datatable in CSV-format into a string.
See function params(...) and all available "csv..."-settings for e.g. "delimiter", "enclosure", "BOM", ... etc.
Syntax
render_csv(): string
setData(...)
Sets the data to rendered as a datatable.
Regard: Which fields (aka columns) are finally being rendered and in which order can configured with the datatable-functions.
Syntax
setData($data): hublify_var_ext_datatable
$data - Two dimensional array.
setHtmlTableClass(...)
Sets the css-class-string that is usually injected into the <table ...>-element.
Syntax
setHtmlTableClass($cssClassStr = null): hublify_var_ext_datatable
sort(...)
Executes a sorting of the data on the given field. This is applied immediately to the contained data.
Syntax
sort(string $field, string $dir = 'asc'): hublify_var_ext_datatable
sorts(...)
Executes a multi-field sort. This is applied immediately to the contained data.
Syntax
sorts(array $params): hublify_var_ext_datatable
$params
@param array $params An array of fields and their sorting direction. [ { 'field': '<field>', // (required) 'dir': '<asc|desc>' // (optional, default "asc") }, ... ]
Properties
HTML Templating
Following properties are used to render the actual html-table source code.
Property | Default | Description |
---|---|---|
htmlTableOpen | <table{%class%}{%style%}> | |
htmlTableClass | hfyDataTable | Sets the css class for the opening <table>-tag. |
htmlTableStyle | null | Sets the css style for the opening <table>-tag. |
htmlTableClose | </table> | |
htmlHeaderOpen | <thead> | |
htmlHeadereClose | </thead> | |
htmlHeaderCellOpen | <th{%class%}{%style%}{%attr%}> | |
htmlHeaderCellClose | </th> | |
htmlBodyOpen | <tbody> | |
htmlBodyClose | </tbody> | |
htmlRowDataOpen | <tr> | |
htmlRowDataClose | </tr> | |
htmlDataCellOpen | <td{%class%}{%style%}{%attr%}> | |
htmlDataCellClose | </td> | |
htmlRowGroupOpen | <tr class="hfyRowGroup"> | |
htmlRowGroupClose | </tr> | |
htmlFooterOpen | <tfoot> | |
htmlFooterClose | </tfoot> |
Examples
Simple
A very simple example. Pure data - no extra configurations.
{# ---- Defining some static data ---- #} {% set myData = [ { 'col1': 'Hello', 'col2': 'World!', 'col3': 10 }, { 'col1': 'Aloha', 'col2': 'Hublify!', 'col3': 50 }, { 'col1': 'Caramba ', 'col2': 'Caracho!', 'col3': 100 }, ] %} {# ---- Creating a datatable-object ---- #} {% set myDataTable = hublify.datatable(myData) %} {# ---- Render the datatable ---- #} {{ myDataTable }}
Example #2
Mixture of
{{ hublify.datatable( myStorageItemDataList ) .dataset('storageitem') .fields([ 'si_name', 'si_amount_nominal', 'si_amount_reorder' ]) .params({ 'lineNumbers': true, 'columnHeaders': true, 'sumsHeader': true, 'sumsFooter': true, }) .fieldDefinition('si_amount_nominal', { 'type': 'float', 'name': 'Nominal', 'htmlHeader': null, 'formatter': null, 'formatterParams': null, }) .fieldDefinition('si_amount_reorder', { 'type': 'float', 'htmlHeader': '✔', }) .group('node_path') .sorts([ { 'field': 'si_amount_nominal', 'dir': 'desc' }, { 'field': 'si_name' } ]) }}
CSV - simple
A very simple example, where the data-table content / data is rendered as a CSV-string.
{# ---- Defining some static data ---- #} {% set myData = [ { 'col1': 'Hello', 'col2': 'World!', 'col3': 10 }, { 'col1': 'Aloha', 'col2': 'Hublify!', 'col3': 50 }, { 'col1': 'Caramba ', 'col2': 'Caracho!', 'col3': 100 }, ] %} {# ---- Creating a datatable-object ---- #} {% set myDataTable = hublify.datatable(myData) %} {# ---- Render (as CSV!) the datatable ---- #} {{ myDataTable.render_csv() }}
CSV - As downloadable file (html, embedded)
For end users it is of course a convinient way to download the datatable's data with one click.
When your template renders output for HTML-Environments, you can pre-render the data as a csv-file-content and embed the csv-content into a clickable Download-Link.
{# ---- Defining some static data ---- #} {% set myData = [ { 'col1': 'Hello', 'col2': 'World!', }, { 'col1': 'Aloha', 'col2': 'Hublify!', }, { 'col1': 'Caramba ', 'col2': 'Caracho!', }, ] %} <a href="data:text/csv;base64,{{ hublify.base64_encode( hublify.datatable(myData) .fields(['col1', 'col2']) .fieldDefinition('col1', {'name': 'Column 1'}) .fieldDefinition('col2', {'name': 'Column 2'}) .params({ 'columnHeaders': true, 'sumsHeader': false, 'sumsFooter': false, }) .render_csv() ) }}" download="hublify_csv_download_{{ "now"|date("Y-m-d_H-i") }}.csv" class="btn btn-primary mb-3" > CSV Download </a>
Custom Formatter
You can easily define own mini-twig-templates to render your field's content.
Remember that inside your twig-formatter-string, you can use the special datatable-vars:
- value
This variable is preset with the current cell's data-value. This can be a string, int, array, object etc. itself! - row[<fields>]
The row-object contains the current line's / record's field-values.
{# ---- Defining some static data ---- #} {% set myData = [ { 'col1': 'Hello', 'col2': 'World!', }, { 'col1': 'Aloha', 'col2': 'Hublify!', }, { 'col1': 'Caramba ', 'col2': 'Caracho!', }, ] %} {# FORMATTER: Inside your formatter, use: "value" and "row" vars! #} {{ hublify.dataTable(myData) .formatterTplStr('col1', '<b>{{ value }}</b>') }}
You can also pass and access arrays and objects as values.
{# ---- Defining some static data ---- #} {% set myData = [ { 'col1': { 'firstname': 'Jane', 'lastname': 'Doe' }, 'col2': 'World!', }, { 'col1': {
'firstname': 'John', 'lastname': 'Smith' }, 'col2': 'Hublify!', } ] %} {{ hublify.dataTable(myData) .formatterTplStr('col1', '<b>{{ value.firstname }} {{ value.lastname }}</b>') }}