simbiat/array2table

Library to convert arrays to table.

2.0.9+20221010 2022-10-10 09:48 UTC

README

This library is used for creating HTML tables using data provided to it in an array. When will you want to use it? I believe, there are 2 use-cases:

  • You are presenting a lot of homogeneous data from your database
  • You are creating some relatively simple form (like user settings) and do not want that much customization for it

Yes, this library can be used for creating forms, that you will be able to process further, once they are submitted. And the most unique feature here is that form elements will not be just text-fields: library supports checkboxes, date/time fields, colors, files, .etc. Each element will be created with the minimum required attributes, with automatically generated IDs and classes (for CSS customization or JavaScript interactivity, if required).

How to use

The best way to understand what you will be getting is a live example, so check out sample.html somewhere near this README. There you will find 3 tables, that were generated using following code:

echo (new \Simbiat\array2table)->setIdPrefix('sem_edit')->setCaption('Semantic, editable')->setFooter(['#func_sum','',''])->setCurrencyCode('USD ')->setCurrencyPrecision(2)->setCurrencyFraction(true)->setCheckbox(true)->setChecked(true)->setEditable(true)->setTextareaSetting('cols', '20')->setTextareaSetting('rows', '5')->setTypes(['number','string',['text','password','tel','date', 'time', 'datetime', 'seconds', 'bytes', 'price', 'checkbox', 'email', 'url', 'html', 'img', 'color']])->generate(
    [
            ['Points'=>'1','Field'=>'Login','Value'=>'Simbiat'],
            ['1','Password','Simbiat'],
            ['1','Telephone','+74991752327'],
            ['1','Date of birth','12-05-1989'],
            ['1','Current time',time(),],
            ['1','Last login',time(),],
            ['1','Seconds','123456',],
            ['1','Image size','1234567',],
            ['1','Salary','123456',],
            ['1','Are you a robot?','No',],
            ['1','Email','simbiat@outlook.com',],
            ['1','Website','https://www.simbiat.dev',],
            ['1','Signature','<a href="https://www.simbiat.dev">Awesome website</a>'],
            ['1','Avatar','https://media.kitsu.io/users/avatars/41172/large.jpg'],
            ['1','Favorite color','006E72'],
    ]
);

echo (new \Simbiat\array2table)->setIdPrefix('sem_nonedit')->setCaption('Semantic, non-editable')->setFooter(['#func_sum','',''])->setCurrencyCode('USD ')->setCurrencyPrecision(2)->setCurrencyFraction(true)->setCheckbox(true)->setChecked(true)->setEditable(false)->setTextareaSetting('cols', '20')->setTextareaSetting('rows', '5')->setTypes(['number','string',['text','password','tel','date', 'time', 'datetime', 'seconds', 'bytes', 'price', 'checkbox', 'email', 'url', 'html', 'img', 'color']])->generate(
    [
            ['Points'=>'1','Field'=>'Login','Value'=>'Simbiat'],
            ['1','Password','Simbiat'],
            ['1','Telephone','+74991752327'],
            ['1','Date of birth','12-05-1989'],
            ['1','Current time',time(),],
            ['1','Last login',time(),],
            ['1','Seconds','123456',],
            ['1','Image size','1234567',],
            ['1','Salary','123456',],
            ['1','Are you a robot?','No',],
            ['1','Email','simbiat@outlook.com',],
            ['1','Website','https://www.simbiat.dev',],
            ['1','Signature','<a href="https://www.simbiat.dev">Awesome website</a>'],
            ['1','Avatar','https://media.kitsu.io/users/avatars/41172/large.jpg'],
            ['1','Favorite color','006E72'],
    ]
);

echo (new \Simbiat\array2table)->setIdPrefix('nonsem_nonedit')->setCaption('Non-semantic, non-editable')->setSemantic(false)->setStyling(true)->setFooter(['#func_sum','',''])->setCurrencyCode('USD ')->setCurrencyPrecision(2)->setCurrencyFraction(true)->setCheckbox(true)->setChecked(true)->setEditable(false)->setTextareaSetting('cols', '20')->setTextareaSetting('rows', '5')->setTypes(['number','string',['text','password','tel','date', 'time', 'datetime', 'seconds', 'bytes', 'price', 'checkbox', 'email', 'url', 'html', 'img', 'color']])->generate(
    [
            ['Points'=>'1','Field'=>'Login','Value'=>'Simbiat'],
            ['1','Password','Simbiat'],
            ['1','Telephone','+74991752327'],
            ['1','Date of birth','12-05-1989'],
            ['1','Current time',time(),],
            ['1','Last login',time(),],
            ['1','Seconds','123456',],
            ['1','Image size','1234567',],
            ['1','Salary','123456',],
            ['1','Are you a robot?','No',],
            ['1','Email','simbiat@outlook.com',],
            ['1','Website','https://www.simbiat.dev',],
            ['1','Signature','<a href="https://www.simbiat.dev">Awesome website</a>'],
            ['1','Avatar','https://media.kitsu.io/users/avatars/41172/large.jpg'],
            ['1','Favorite color','006E72'],
    ]
);

Here's what the code does:

  1. Create new object with (new \Simbiat\array2table). Obviously load the library before that.
  2. Optionally set a prefix for elements' IDs and Classes with setIdPrefix('prefix'). Very useful, in case you will have multiple tables like that on one page, like sample.html does.
  3. Optionally set caption for the table with setCaption('caption'). If this is set a <caption></caption> will be added to the table if it's semantic or respective <div></div> if it's not. Basically, this is a name of the table.
  4. In case of non-semantic tables we have setSemantic(false). This forces use of <div></div> elements instead if regular (semantic) table elements (table, td, tr, th, .etc). When creating actual tables, it is recommended to use semantic approach (thus default is true), but in some cases you may want to have <div></div>.
  5. Optionally enable basic styling for <div></div> elements for non-semantic approach with setStyling(true). This will add inline style attributes to make non-semantic table look more like its semantic counterpart. Styling is based on WebKit stylesheet at the time of writing.
  6. Optionally set footer with setFooter(['','','']). If this is set <footer></footer> will be added to the table if it's semantic or respective <div></div> if it's not. This is a row that will appear at the bottom of the table. If set, its length will be checked against the number of columns the data have and if different - throw an exception. footer can be used to repeate header with setFooterHeader(true). In case of sample.html we also use #func_sum to calculate total (sum) of the values in respective column.
  7. Optionally set currency for currency values with setCurrencyCode('USD '). Adding space at the and of the value will place the currency before the values. Default is '', that empty string.
  8. Optionally set precision for currency values with setCurrencyPrecision(2). This determines number of digits after dot. Default is 2.
  9. Optionally set initial format used by currency values with setCurrencyFraction(true). If true converter will expect values to be "fractions", like cents for USD, thus will consider the last 2 digits of a value as cents and put them after the dot. If false - will expect a float and/or convert to it.
  10. Optionally add checkbox for each lie with setCheckbox(true). This may be useful when you want to allow user to remove some entries, for example. Set is as checked with setChecked(true).
  11. Optionally make the values of the table editable with setEditable(true). This will replace values with appropriate <input> elements.
  12. Optionally adjust size of <textarea> elements with setTextareaSetting('cols', '20')->setTextareaSetting('rows', '5').
  13. Set values types with setTypes(['number','string',['text','password','tel','date', 'time', 'datetime', 'seconds', 'bytes', 'price', 'checkbox', 'email', 'url', 'html', 'img', 'color']]). In the example 2 first columns (array elements) have one type for all values in them. Both of them are not, actually, a supported type from the list, thus they will turn into regular <span></span> elements. The 3rd column uses an array of types with separate type for each row. It's not required to have different types for each: this is done only for the sample purpose to showcase all of currently supported types. It is required to have the same number of types as you have actual data rows or an exception will be thrown.
  14. Actually generate the table with generate( [ ['Points'=>'1','Field'=>'Login','Value'=>'Simbiat'], ['1','Password','Simbiat'], ['1','Telephone','+74991752327'], ['1','Date of birth','12-05-1989'], ['1','Current time',time(),], ['1','Last login',time(),], ['1','Seconds','123456',], ['1','Image size','1234567',], ['1','Salary','123456',], ['1','Are you a robot?','No',], ['1','Email','simbiat@outlook.com',], ['1','Website','https://www.simbiat.dev',], ['1','Signature','<a href="https://www.simbiat.dev">Awesome website</a>'], ['1','Avatar','https://media.kitsu.io/users/avatars/41172/large.jpg'], ['1','Favorite color','006E72'], ] Each "inner" array in "outer" array represents a row, while each element in "inner" arrays - respective column. In sample 1st row is using an associative array for optional header value (creates <header></header>). Alternatively setHeader([]) can be used to the same effect.

Data types

Type Input element Description
date <input id="element_count" class="element_class" type="date" step="1" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" value=""> If Simbiat\SandClock library is registered will attempt to show date according to its logic, otherwise will keep the value as is. If editable, will enforce certain format for the value, when sending the form.
time <input id="element_count" class="element_class" type="time" step="1" pattern="[0-9]{2}:[0-9]{2}:[0-9]{2}" value=""> If Simbiat\SandClock library is registered will attempt to show time according to its logic, otherwise will keep the value as is. If editable, will enforce certain format for the value, when sending the form.
datetime <input id="element_count" class="element_class" type="datetime-local" step="1" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}" value=""> If Simbiat\SandClock library is registered will attempt to show date and time according to its logic, otherwise will keep the value as is. If editable, will enforce certain format for the value, when sending the form.
seconds <input id="element_count" class="element_class" type="number" step="1" min="0" inputmode="decimal" value="value"> If Simbiat\SandClock library is registered will attempt to convert seconds to time length according to its logic, otherwise will keep the value as is. If editable, will attempt to force decimal virtual keyboard, depending on browser support
bytes <input id="element_count" class="element_class" type="number" step="1" min="0" inputmode="decimal" value="value"> If Simbiat\CuteBytes library is registered will attempt to convert bytes to other sizes according to its logic, otherwise will keep the value as is. If editable, will attempt to force decimal virtual keyboard, depending on browser support
price <input id="element_count" class="element_class" type="number" step="0.01" min="0.00" inputmode="decimal" value="value"> Converts provided value into a float with an optional currency sign representing an amount of that currency. If editable, will attempt to force decimal virtual keyboard, depending on browser support
checkbox <input id="element_count" class="element_class" type="checkbox"> Converts value to a checkbox. Values like yes, no, on, off will be converted to true or false, while for others boolval will be used for the same. If result is true - checkbox will be ticked (checked attribute added). If not editable, disabled attribute will be added.
email <input id="element_count" class="element_class" type="email" inputmode="email" value="value"> Returns element using mailto: URI if validates as actual email. If not - will be treated as regular text in . If editable and browser implements input type email - will validate the value when sending form.
url <input id="element_count" class="element_class" type="url" inputmode="url" value="value"> Returns element if validates as actual email. If not - will be treated as regular text in . If editable and browser implements input type url - will validate the value when sending form. If Simbiat\PrettyURL is registered, will sanitize the value before processing.
html <textarea id="element_count" class="element_class" cols="cols" rows="rows" minlength="minlength" maxlength="maxlength" spellcheck="true">value</textarea> Treats string same as textarea, but sanitizes the value beofre processing.
textarea <textarea id="element_count" class="element_class" cols="cols" rows="rows" minlength="minlength" maxlength="maxlength" spellcheck="true">value</textarea> Shows text as . If editable, shows appropriate textarea. **Be extremely careful with the text you allow users to input here, because it can be easily exploited! Use some kind of sanitization process when submitting form!**
text <input id="element_count" class="element_class" type="text" inputmode="text" value="value"> Returns regular text or respective element.
tel <input id="element_count" class="element_class" type="tel" inputmode="tel" value="value"> Same as text, but will enforce specific virtual keyboard if browser supports it.
password <input id="element_count" class="element_class" type="password" inputmode="password" value="value" pattern="password_pattern"> Same as text, but will clear the value (always) and apply pattern. Pattern is stored as public static $PasswordPattern and can be changed if you want to, but it's advised against in order to comply with the minimum complexity recommendations.
img <input id="element_count" class="element_class" type="file"> If not editable, returns element with source equal to value provided. Otherwise acts same as file.
file <input id="element_count" class="element_class" type="file"> Provides field for file upload, if editable (if not, the element will be disabled). Use setMultipleFiles(true) to allow upload of multiple files.
color <input id="'.${$string_type.'id'}.'" class="'.$prefixId.'_color" type="color" value="#ffffff" pattern="^#?([a-fA-F0-9]{6})$"> Returns color picker if supported by browser. No need to send # when providing data, since it will be added automatically.

Settings

Setter function Default value Description
setSemantic(bool $semantic) true Generate <table> (semantic) if true or <div> (non-semantic) if false.
setStyling(bool $styling) false Force basic inline styling for <div> variant. Custom styling is recommended.
setCheckbox(bool $checkbox) false Generate with first column being a checkbox with unique ID if true. Works for multi-arrays only.
setChecked(bool $checked) false Generate with first column checkbox checked if true.
setSanitize(bool $sanitize) true Attempt to strip tags and encode HTML entities, unless html data type.
setEditable(bool $editable) false Flag to allow edit of the editable fields.
setCaption(string $caption) '' Optional caption (name) for tables.
setHeader(array $header) [] Optional header for tables. Expects array with same length as number of columns in data provided. Alternatively will attempt to use keys from first row, if it's an associative array.
setRepeatHeader(int $repeatHeader) 0 If value is not 0, will repeat header every X number of lines, where X is the value set by this setter. Recommended for large tables.
setFooter(array $footer) [] Optional footer for tables. Expects array with same length as number of columns in data provided. Supports functions for columns with singular data type: '#func_sum' (sum of all values in column), '#func_avg' (average of all values in column), '#func_min' (lowest value in column), '#func_max' (maximum value in column)
setFooterHeader(bool $footerHeader) false Use header text in footer.
setColGroup(array $colgroup) [] Setter for optional colgroup definition, which allows grouping of columns through HTML classes. Expect array like [['span'=>2,'class'=>'col_class','style'=>'col_style'],[...],...,[...]]. 'span' expect a numeric value identifying number of columns in a group. 'class' expects a class that will be additionally applied to the group. 'style' expects a CSS style string that will be additionally applied to group.
setTypes(array $types) [] Optional list of types to be applied to columns and rows. Expects an array in format as described in [How to use](#how-to-use).
setIdPrefix(string $idPrefix) 'simbiat' Optional prefix for elements' IDs and some of the classes.
setMultipleFiles(bool $multipleFiles) false Option to allow multiple files upload for file fields.
setDateFormat(string $dateformat) 'Y-m-d' Date format to use with Simbiat\SandClock library for date type.
setTimeFormat(string $timeFormat) 'H:i:s' Time format to use with Simbiat\SandClock library for time type.
setDateTimeFormat(string $dateTimeFormat) '' Date and time format to use with Simbiat\SandClock library for date type. If empty will combine date format and time format set by respective setters as date time.
setLanguage(string $language) 'en' Language to use with Simbiat\SandClock library for seconds type.
setTextareaSetting(string $setting, string $value) [ 'rows'=>'20', 'cols'=>'2', 'minlength'=>'', 'maxlength'=>'', ] Customization options for textarea elements.
setCurrencyCode(string $currencyCode) '' Set an optional currency code (or symbol) for price type. Add space at the end to put it before the value.
setCurrencyPrecision(int $currencyPrecision) 2 Set precision of floating point (number of digits after the dot) for price type.
setCurrencyFraction(bool $currencyFraction) true Set to false to treat values for price type as floats. Treat values as fractions (like cents in case of USD) by default.