Introduction

Components

Frontend

  • driven by JavaScript and jQuery
  • based on powerful libraries
    • Bootstrap
    • Tabulator
    • Jsonform
    • Dropzone
  • easy to use templates

Backend

  • MySQL
    • your table structrue
  • PHP
    • Data Access class
    • Data Access Rules
    • Ajax interface
  • JSON
    • Datadefinitions
  • HTML
    • Snippets

Local formats

Internal formats

The internal format for the decimal point is ".", for a date time is: YYYY-mm-dd hh:mm:ss. PHP is not used for formatting. But the number format and date format should regard the local formats. The formatting will be done in the client browser.

English is the defauflt format

K8 Web Construction Kit use the html 5 date and number form input elements. The format of this fields depends on the web browser.

  • forms with html 5 formats
  • tabulator with format strings
  • html output with tabulator format strings too

Date and number formats

The format in the record list with tabulator is defined with placeholders:

  • GLOBALS_decimal_point='.'
  • GLOBALS_thousands_sep=','
  • GLOBALS_tabulatordateformat='MM/DD/YYYY'
  • GLOBALS_tabulatortimeformat='h:mm a'
  • GLOBALS_tabulatordatetimeformat='MM/DD/YYYY h:mm a'

Setting the format

In BasicFunctions.php the function mylocale() is called. It reads the $_SERVER['HTTP_ACCEPT_LANGUAGE'] and compares it with the language string:

AM, AR, AT, AZ, BA, BE, BG, BO, BR, BY, CA, CH, CL, CM, CO, CR, CY, CZ, DE, DK, EC, EE, ES, FI, FO, FR, GE, GL, HR, HU, ID, IS, IT, KZ, LB, LT, LU, LV, MA, MD, MK, MO, MZ, NL, NO, PE, PL, PT, PY, RO, RS, RU, SE, SI, SK, TN, TR, UA, UY, UZ, VE, VN, ZA

If the browser language is in this string, the following changes are made:

  • GLOBALS_decimal_point='.'
  • GLOBALS_thousands_sep=','
  • GLOBALS_tabulatordateformat='DD.MM.YYYY'
  • GLOBALS_tabulatortimeformat='HH:mm'
  • GLOBALS_tabulatordatetimeformat='DD.MM.YYYY HH:mm'

The date is changed to german. All other formats have to be implemented by yourself. The format string is explained in Moment.js.

Language Support

In the <head> the Javascript language file is linked:

The domain language shortcut is added to the filename to load the desired language.

The language files contains 2 arrays: text and textnew. The function getL(expression,placeholders[]) gives the translation back. If the expression is not in the array text, the expression is added to textnew and the original expression is given back.

Javascript Support:

  • getL(word,placeholder[])
    return value: text[word], $1, $2, $x is replaced by the array values
  • ReplacePlaceholder(str,obj,...)
    the function ReplacePlaceholder replaces all: #ls#<string># with the value of the text-array.
  • nestedLoop(settings)
    looks for #ls# and calls the ReplacePlaceholder function

Example for german, the language file, masterdata/js/lang_sys_de.js.js:

Website Template <file>.php

Structure of PHP-Files

  • <?php PHP Init
    • _init_page.php
      • masterdata/_init.php
        • global variables
        • includes for datadefinition and login
      • session_start()
      • include "masterdata/BasicFunctions.php"
      • set pages array
      • set menu array
      • init variables from $_GET
      • check database connection: isset($GLOBALS['k8db'])
      • init laguage support
      • include loginlogout_execute.php
      • session loss / cookie
      • set SESSION[domain_language]
      • $headtitle=$domain_name
      • $headdescription
      • $_GET Parameters
    • (masterdata/datadefinitions.php)
    • (masterdata/class_data_accessclass.php)
    • page=detail, load definition, load recordset
  • <html>
    • html lang=$domain_language
    • <head>
      • $headtitle
      • $headdescrtiption
      • _head_example.php
        • script declaration
        • CSS files
        • your libraries
        • masterdata/js/lang_sys_'.$domain_language
        • datadefinition head[] (JavaScript)
        • pages head[] (JavaScript)
      • _head_js.php
        • head_include (head_includedefault=true)
        • Variables from PHP
        • datadefinition settingsadditional[]
      • datadefinition head_end[] (JavaScript)
    • <body>
      • Page header with menu
        • _header_example.php
          • page banner
          • menu
      • Content
        • pages contentPHP (PHP-File)
        • masterdata
        • listing
        • html element
      • Page footer
        • script js/example.js
        • _footer_kit.php
          • legal notice
          • contact
          • bootstrap script
        • datadefinition foot[]
        • pages foot[]

_init_page.php

pages-array

structure of array pages[$_GET[page]]:

  • url
  • helpurl
  • login
  • datadefID
  • layout
  • js_display (masterdata1 or html1)
  • headtitle
  • headdescription
  • head
  • contentPHP
  • foot
Check cookie and login

If a login-cookie is set and the $_SESSION[userID] is lost, the user is logged in by the cookie again.

If an pages which requires a login is called, a redirect to the login is executed.

language support

the language can set by:

  • $_SESSSION[domain_language]
  • $_GET[domain_language]
  • $_SERVER['HTTP_ACCEPT_LANGUAGE']

Only languages set in the global array "domain_languages" are accepted.

masterdata/_init.php

Global variables:

  • for domain
    • title and description
    • language
    • name and email
  • for include
    • domain_datadeffiles
    • domain_selectfiles
    • [domain_includes]
      • login
      • logout

The include files allows to write individual project code in your project folder

_prepare_head.php

The datadefinition is loaded. The head meta data are prepared here:

  • title
  • description

This are the dependencies with a datadefinition:

  • datadefID set:
    • keyvalue set
      • headertitlecolumn
      • headerdescriptioncolumn
    • else
      • headertitle
      • headerdescription
  • else
    • domain_name
    • domain_description

more dependencies with a datadefinition:

  • head
    [this array lines are inserted into <head>]
  • head_include
    [all php array elements are includes into <head>]
  • foot
    [this array lines are inserted at the end]

If you insert an Javascript file at the end ("foot") this replaces the Standard Javascript file "example.js". So you have to append the elements by your self to the right html tags.

_head_js.php, Javascript variables from PHP

Here are variables from the PHP Locals trasferred to get a sophisticated date and number formatting.

The settings of the datadefinitions are also defined here.

_header.php, the navigation

2 Options:

  • menu with PHP and HTML
  • menu by JavaScript with js/menu.js

index.php (Website)

URL-Parameters:

  • page
    • Home
    • Register
    • My data
    • User list
    • Login
    • Contact
    • LegalNotice
    • Masterdata
    • List
    • Form
    • Html
    • Detail
    • Catalog
    • Lineedit
  • datadefID
  • page_mode (1=no header and footer)

SESSION lost

The web server ends automatically a session after a fixed period of inactivity. The following methods are provided to avoid errors:

  • automatic login by cookie
  • page timer with redirect to login without cookie
Automatic login by cookie

By login a cookie with the login data is set. If a data request requires a logged in user without that a user is logged in the cookie is read and user is logged in again.

Page timer

Without cookie the object k8pagetimer is initialized and an interval is set. By each Ajax request the interval is set back to maximum. If the maximum time is over the login page is called.

Pages array

The page array allows to configure the following properties

  • url
  • datadefID
  • helpurl
  • login

If a page with the property: login=true is requested, the login of the user is checked. If the user is logged in, the page is displayed, otherwise the url is saved and the login page is called. After succesful login the initial page is displayed.

element.php (Website template)

This website template contains header and footer.

Parameters:

  • page:
    • for recordsets
      • masterdata or empty
      • list
      • html
      • catalog
      • lineedit
    • for 1 record
      • detail
      • form
  • datadefID

The important meta data in a website are:

  • titel, $headtitle
  • description, $headdescription
for recordsets

detail, form

By form and detail the parameter keyvalue specifies the desired record.

the data is already read with php. The title and description in the head meta is filled out. To transfer the data to javascript use this command:

var data=<?php echo json_encode($dataws,JSON_NUMERIC_CHECK);?>;

You can also use it as template for your individual website.

objectdata_form.php (Test-File)

This file is for testing your datadefintion. In this simple file the login file is implemented. The following elements are supported:

  • page
    • Masterdata
    • List
    • Form
    • Html
    • Detail
    • Catalog
    • Lineedit
  • datadefID

masterdata_form.php (Test-File)

This easy template displays a masterdata form. Its implemented for compatibilty reasons.

JavaScript / jQuery

Plugin masterdata

well known invoice

The masterdata plugin displays 3 elements:

  • master data form
  • listing (only the list)
  • form (only the form)

Plugin searchbox

well known invoice

The searchbox opens the listing as overlay. With the filter line the right record is searched. With a click on the record all record data is transfered to the result function and the overlay is closed.

Plugin catalog (HTML)

well known invoice

The catalog plugin displays 1 or more records. It supports the modes:

  • catalog
  • detail
  • line edit

object k8.displayImage

well known invoice

The mode defines:

  • mode=0, single image
  • mode=1, multiple images

User and Registration

Frontend

  • Registration, my Data, add Friends
    • index.php?page=register
      • register
      • my data
      • picture upload
      • add friends
      • user searchbox
  • Login, Logout, send Password
    • dialogs:
      • login
      • logout
      • send password
    • snippets:
      • _loginlogout_execute.php
      • _loginlogout_form.php
  • Admin
    • user list

Backend

  • Tables
    • k8login
    • k8loginfriends
  • functions, BasicFunctions.php
    • login($name,$pwd,$error,$rememberme=0)
    • logout()
    • Send Password
      gbSendPwd($postfields,&$error,&$message)
  • datadefinitions
    • 5, table: k8login
      • k8login.json
    • 6, table: k8loginfriends
      • k8loginfriends.json
    • 7, table: k8login, search user
      • k8login_searchuser.json

Registration, my Data, add Friends

Registration

Registration and My Data is displayed by index.php?page=register. Here are 3 datadefintions involved:

  • 5, k8login.json
  • 6, k8loginfriends.json
  • 7, k8login_searchuser.json

For the registration only k8login.json is necessary. The default value for roles is set in the datadefinition (k8login.columns.roles). Actual this are the roles: 3:member and 5:friends.

After succesful registration the login page is opened:

My Data

You can change your data and also upload an image. Additional to the registration you also can add friends. In the datadefinition "k8login.json" the setting masterdata.addfriends:true determines if the "Friends" table is shown. With "+" the user searchbox is openend.

Of course you an add you own fields and add more functionality due to your application.

Properties in the datadefinition, masterdata (bootstrap5):

  • upload: enabled:true
  • showdelete:true
  • showsetdeleted:true
  • addfriends:true

Search User

This Searchbox depends on the datadefinition "7". Only userID and username are read. By click on the line the user is added to the friends list.

Login, Logout, send Password

Login / Logout

you have the following 3 views:

  • login with username and password
  • logout button, actual username is displayed
  • send password with username and email

Where to build it in?

_loginlogout_execute.php

include it after "_init_page.php". The PHP functions for: login, logout and send password are called.


_loginlogout_form.php,

include it in your HTML exactly where you want to display the form. It contains the form and Javascript for the user interface.

Master data form

masterdataform

Master data form on the fly: Call it with your table and get automatically a master data form!


Generate a datadefinition and configure the list columns and the form with JSON to get it functionally and good looking!


Listing record functions:

  • List
  • Sort
  • Filter

Crud functions:

  • Create, New record
  • Read, Load record
  • Update, Save record
  • Delete record

Features

  • automatic generated
  • easy to use
  • various configurations

Examples

  • Masterdata classic
  • Masterdata form only
  • Objectdata
  • Master detail

to the examples: Master data

Call and return values

returned properties and methods

  • el_md, the masterdata element
  • update,
  • tableTab, the tabulator object
  • changes,
  • getRow(), the actual tabulator.row object
  • message
  • insertRecord
  • gObject2FormBuild
  • setDirty
  • setElementValue

Master data HTML

datadefinition

  • name: displayed in the form headline
  • table: if columns is not defined, the table structure is read and stored in the columns array
  • key: Primary key field of the thable
  • objectclass: name of the data access class
  • requiredfile: php file of the objectclass
  • masterdata:
    • formmode:2
      (1: html in html/main)
      (2: default for jsonform)
    • urls for the data access
  • columns: array of the table fields. The "column" part of the definition is important for the data access class. Only this fields are saved to the database
  • tabulator: definition for the recordset list in the header
    please change the listing here!
    • selectable, display selectable checkbox
  • jsonform: HTML snippets
    please change the form here!
  • jsonform_conf: configuration of vertical and horizontal form
  • html
    • main: complete html for form
Default values

Default values for the form are set in masterdata.defaultvalues:

Menu / Dropdown

build up the menu:

  • Options (masterdata.menuleft_options=true)
    • utf8 CSV Export
    • Excel Export
    • PDF Export
  • menuleftformhtml for form
    • ...
  • menulefthtml for list
    • ...

Formmode

Formmode 1: html

You create your own html. Put it in the datadefinition (<your project path>/_datadefinition.php):

html.masterdata.main=<your html>

please pay attention:

  • without form tag
  • with buttons and message

form group with submit button:

Formmode 2: jsonform

This are the properties for jsonform:

  • jsonform
  • jsonformconfig

Jsonform also has additional validation rules. More to jsonform in our Fundamentals jsonform.

Formmode 3: k8form (under construction)

k8form is an easy generator of bootstrap forms. Insert this in your datadefinition:

controls and call back functions

controls

  • new
  • edit / click on line
  • delete
  • save
  • cancel

call back functions

  • dataCreateStructure(el_md,dat)
  • dataMenuleft(el_md,e,row_actual)
  • dataNew(el_md,dat)
  • dataLoad(el_md,dat)
  • dataChange(el_md,el)
  • dataPrepareSave(el_md)
  • dataBeforeSave(el_md,dat)
  • dataAfterSave(el_md,dat)
  • newRecord(el_rec_record,dat)
  • onDelete(el_rec_record,e.target)

Example for dataChange(el_md,el)

k8 Forms

k8 Forms

K8 forms

K8 Forms allows you with HTML snippets and a Json datastructure to create input forms.

Features:

  • K8 Web Kit generates from a table a k8 form structure automatically.
  • You can add attributes and own data-attributes as you like it.
  • Containers, like <div> or <fieldset> can be nested and consist own field arrays.
  • Individual HTML snippets can be added and used in the fieldwraptemplates
  • Fields in nested containers are automaically listed in a "formcollection"

Formatting numbers with decimal places:

gFormatinputfordisplay(element,value)

Even with a "step" tag the decimal numbers are not formatted well, so the formatting function is called on change.

k8-form structure

Choose the template first. Please change then the structure and "Create form" to see the result:

Resulted Form

Object properties

k8.createform(options):

All HTML snippets from the section: html.masterdata can be used as fieldwraptemplate:

"fieldwraptemplate":"{{myfieldwraptemplate}}"

fields:

The following HTML tags are supported:

  • input
  • select
  • textarea

The following input types are supported:

  • hidden
  • text
  • number
  • checkbox
  • radio
  • date
  • time
  • ...

More HTML Code can be placed in:

  • fieldwraptemplate
  • fieldtemplate

Atrributes can additionally added as string to 'input_attributes'.

inputgroup:

All fielda are enumerated beginning with {{field0}}.

options:

All properties are appended as attribute.

or:

containers

This is an example for a form with 2 blocks:

Using k8form

Direct display

k8form.createform gives back the HTML form. But this is not needed in this example. If a selector is defined, in this case '#myform', the form is directly displayed in the element.

With init first

With the function k8form.initFormfields(options) a collection of the fields 'formcollection' is build up:

formcollection['name/identifier']

In the formcollection each field is listed as a pointer to its origin. This allows you to change the field properties easyly.

Later the 'settings' object is transfered to the master data plugin.

Templates

Template structure

  • template
    • fieldwraptemplate
      • labeltemplate
      • fieldtemplate
    • fieldwraptemplate_radio
      • labeltemplate_radio
      • fieldradiotemplate
        • texttemplate
        • fieldtemplate
    • fieldwraptemplate_checkbox
      • labeltemplate
      • fieldtemplate

form template

fieldwraptemplate horizontal form

labeltemplate

fieldtemplate

containers template

fieldwraptemplate_radio horizontal

fieldradiotemplate

Examples

Overlay Form

How to prepare a small dialog with 2 fields and a button:

Form <=> JavaScript

form to JavaScript

Not all form elements can easily exchanged by value. Thease functions help you with the data exchange:

Functions
  • obj2form(obj,el_form,bonlyadd)
  • form2obj(el_form)
  • $(el_form).serializeJSON({checkboxUncheckedValue: "0"})

The differences to the PHP handling are:

  • checkbox: unchecked returns 0
  • disabled fields are also returned

Form

Json Source/Result

  • please take care to write Json here
  • with ->Form you fill the form
  • change the form data
  • with submit you get back result

Please edit and press "->Form"

Form validation

form to JavaScript

Validation is an important subject by data entry. The most common validations are by:

  • HTML
  • JavaScript
  • PHP

HTML Validation

This are the HTML validation related attributes:

  • pattern
  • min
  • max
  • required
  • step
  • minlength
  • maxlength

For more details look at: Mozilla Contraint validation

CSS

This are the CSS pseudo classes for validation:

  • required
  • valid
  • invalid

All invalid elements show a red exclamation mark: exclamation mark

Valid required inputs show a green checked symbol: checked symbol.

The submit event only takes effect after the HTML validation is successful.

JavaScript Validation

This is the call back function of the datadefinition:

dataBeforeSave(el_md,dat,settings);

The process of validation:

  • remove the invalid class for all elments
  • checked element is invalid:
    • set the invalid class for this element
    • 1st invalid element?
  • focus the 1st invalid element
  • if necessary, output a message

Example of a JavaScript validation with masterdata form:

PHP Validation

The masterdata data access class implemented the following checks:

  • field is included in the table
  • data entry valid for the SQL column type
  • required by insert

The datadefinition uses the following include for validation:

An error in this validation is returned by Ajax and displayed in the message tag.

Example of PHP validation with masterdata data access class:

Toggle Form elements

Example for Toggle

This is the toggle area!

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet.

Toggling elments helps to display and hide content. This is an easy HTML Structure to toggle page area:

this jQuery code needs to be added in the foot of the page:

form structure

The elements constitute a bootstrap from:

  • template (for the form)
    • fieldwraptemplate
      • labeltemplate
      • fieldtemplate
template (for the form)
fieldwraptemplate
labeltemplate
fieldtemplate

Listings with tabulator

list with filterform

based on tabulator

  • powerful Tool
  • various configurations
  • easy to adopt

Templates

  • Listing with control elements
  • Search list

Examples

  • List with controls
  • List with filterform
  • List with Line Edit
  • Search box
  • <select> list

to the examples: Listings

Html Output

html catalog

Templates

  • Catalog
  • Detail Page
  • Line Edit

Controls

  • Standard
    • js_rec_new
    • js_rec_edit
    • js_rec_delete
  • Extend for line edit
    • js_rec_save
    • js_rec_cancel
  • block own controls
    • js_rec_control by edit

Structure

  • html class
    • js_rec_container
      • js_rec_head
      • js_rec_records
        • js_rec_record data-keyvalue="10" data-rec_index="0"
        • js_rec_record data-keyvalue="15" data-rec_index="1"
      • js_rec_foot
  • JavaScript methods
    • External Methods
      • replaceRecord(dat,selector)
      • insertRecord(dat,selector,method)
        first,before,after,last

Edit methods (edittype)

  • 0 no controls
  • 1 insert with reload
  • 2 overlay
  • 3 innerHTML
  • 4 new tab
  • 5 new window
  • 6 own line in catalog template
  • 7 own line with special template
  • 8 jsonform in plugin
  • 9 link in this window

Pagination

the pagination parameters:

  • pagination=internal (default) / external
  • paginationsize=0 (default),you have to set paginationsize>0
  • paginationscale=[10, 25,50]
  • paginationalways=false
  • paginationtemplate (HTML Template)
  • masterdata.paginationtemplatebtn (HTML Template)

Plugin catalog

this example is an overview for

  • calling the plugin "catalog"
  • call back functions
  • "methods"

Specials

  • smart Controls
  • conditional Output
  • loop arrays
  • load elements (planing)

Conditional Output

Condition

The condition has to be a valid JavaScript expression:

  • JavaScript variables
  • the actual dat-Array, example:
    dat['creatorID']
  • all JavaScript functions
  • placeholders like #ls#mytext#
Mode

The following modes are supported:

  • hide
  • hidechildren
  • remove
  • empty

Loop array

data-loop_object

The data-loop_object contains the name of the array.

data-loop_html

The data-loop_html contains the name of the datadefinition[html] element

With data-loop_html

normal placeholders

Without data-loop_html

The placeholders contain an asterix: "[image_orientation*]" or "{{image_orientation*}}"

Examples

  • HTML Catalog
  • HTML Detail
  • HTML Line Edit

to the examples: HTML Output

Image Support

html catalog

assign images to your main recordset / object:

  • by reading the main recordset, the following columns are added:
    • image_ID
    • image_file
    • image_orientation
    • image_aspectratio
    • image_width
    • image_height
    • image_count
    • image_array
      • array with images, same the columns above

Advantages

  • easy assignement to object
  • smart in different elements

Frontend

  • Upload
    • add image upload in your form
      • 1 image only
      • any images with gallery
    • <head> for image upload the dropzone libary is refered:
      <link href="css/dropzone.css" type="text/css" rel="stylesheet"&>
      <script src="js/dropzone.js"></script>
    • upload of the images is made with dropzone.js. Reference of the image:
      • basetype: object or table name
      • baseID: ID or key value of the object
      • type: "image"
    • masterdata.js k8.displayImage({options})
      upload, display, delete, sort
  • Display
    • display images on your page
      • catalog with the first image only
      • image with thumbnail list
  • css, to display the images in a cube css classes are added in masterdata.css

Backend

  • images and refrences to the main objects are stored in the table: k8reference
  • the datadefinition is defined in k8references.json with datadefID=8
  • all images are saved in the folder:
    uploads
  • image file name is the: object name + k8references.ID
  • datadefintion
    • masterdata
      • upload
        • enabled:true
        • settings:
          • dropzone
          • for more parameters look in k8.displayImage()

Upload images

3 different states are coded:

  • blank, no base object ist selected, no upload, dropzone is not displayed
  • dropzone, the base object has no image yet, you can upload a new image with dropzone
  • with Image, images are displayed, you can delete the image

Upload image configuration

the k8 library offers the function "displayImage". Display a single image or multiple images can by configured by the mode (0 or 1)

the necessary configuration:

  • (selector)
  • basetype
  • for image upload:
    • baseID
    • parent_rightuser_update
    • mode:
      0=upload 1 image
      1=upload multiple image

the full configuration:

Examples

  • Upload 1 image
  • Upload multiple images
  • Display 1 image in catalog
  • Image with thumbnail list

to the examples: Image Support

Datadefinition

Datadefinition

  • Table, Columns, Childs
  • Masterdata
  • Tabulator
  • K8 Forms
  • HTML
  • JavaScript, jQuery

Example of a datadefinition 1

Generate a new datadefinition from your table

The datadefinition contains details for reading, saving and displaying a recordset. For more informations look: datadefinition.

The following steps are necessary to create your own datadefinition:

  • create your project folder: <myproject>
  • create your table: <your table>
  • define your datadefID: <your datadefID>
  • generate your datadefinition
    • here, have a look to:
      new datadefintion
    • in your developement:
      get_datadefinition.php?table=<your table>&datadefID=<your datadefID>
  • <your datadefID> numeric or alphanumeric?
    • numeric datadefID:
      • save the datadefintion in your folder <myproject> with the name <your table>_<your datadefID> as json file.
      • open or create myproject/_datadefinitions.php
      • add the php code in (look beneath)/_datadefinitions.php
    • alphanumeric datadefID:
      • 1st create a new folder <your datadefID> in your folder <myproject>
      • save it with the name <your datadefID> as json file.
  • look in your browser:
    index.php?datadefID=<your datadefID>&page=masterdata

myproject/_datadefinitions.php (replace the placeholder):

Extend the datadefinition with JavaScript

The datadefinition is extended with fhe JavaScript file: "datadef_extended.js". A JavaScript extension need to be declared in the datadefinition:

An example for the use of call back functions is in the pages example. To bind tinymce to the textarea "content" 4 call back functions are used:

All definitions to read, edit, display or delete your data object are made in the different sections of the data definition.

Generate automatically a new datadefinition for your table; have a look to the Master Data Exercise.

Signification of the properties (under construction):

  • datadefID: ID in the datadefinitions array
  • name: displayed in the form headline
  • table: if columns is not defined, the table structure is read and stored in the columns array
  • key: Primary key field of the table
  • objectclass: name of the data access class
  • requiredfile: php file of the objectclass
  • masterdata: masterdata details of the datadefinition
  • columns: array of the table fields. The "column" part of the definition is important for the data access class. Only this fields are saved to the database
  • tabulator: definition for the recordset list in the header
    please change the listing here!
  • jsonform: definition for the fields in the form
  • jsonform_conf: configuration of vertical and horizontal form
  • k8form: definition for the fields in the form
  • html: definition for the fields in the form

page building:

  • headtitle: title of page
  • headdescription: description of page
  • headimage: facebook "og:image"
  • headtitlecolumn: title from table column
  • headdescriptioncolumn: description from table column
  • headimagecolumn: image from table column
  • head[]: for script and style definition
  • head_include: get variables fromp PHP
  • head_includedefault: true -> include "head_js.php"
  • head_end: add JavaScript to datadefinition
  • foot[]: add JavaScript

tabulator, used properties:

  • ajaxFiltering":true
  • "height":205
  • "layout"=>"fitColumns", to spread the columns along the whole list width
  • columns
    • name
    • title
    • headerfilter (true ,false)
    • headerSort (default:true, false)
    • width (in px)
    • align (left|center|right)
    • formatter: money, date
    • formatterparams, http://tabulator.info/docs/4.4/format#format-builtin)
    • date (http://tabulator.info/docs/4.1/format)

jsonform, used schema properties:

  • name
  • title
  • type (string, number, integer, boolean, array, object)
  • step ("0.01" allows 2 decimal places)
  • required
  • maxLength
  • enum (for select,['value1','value2'])
  • readOnly
  • default

masterdata:

  • script_depth
  • include
  • defaultrights
  • rights
  • sql_statment
  • sql_derived
  • sql_orderby
  • sql_limit
  • filters
  • heartbeat
  • root
  • url_new
  • url_edit
  • url_getR
  • url_init (not used yet!)
  • url_load
  • url_save
  • url_del
  • url_readfilter
  • data_readfilter
  • clause
  • keyvalue
  • defaultvalues (different structure for masterdata and catalog)
  • message_position
  • htmlout
  • edittype
  • window_mode
  • placeholder_mode
  • object_mode
  • add_empty_rec
  • auto_save
  • init_after_save
  • childs_deletetrigger
  • menulefthtml
  • bresize
  • upload (enabled: ...,)
  • notabulator
  • bnoform
  • bwithdirty
  • headline
  • formwrapper
  • footline
  • jsonformID
  • rightuser_create
  • dataNew
  • dataLoad
  • dataBeforeSave
  • dataAfterSave
  • dataMenuleft
  • onDelete
  • newRecord
  • dataChange
  • dataAfterLoadAll (catalog)
  • dataAfterinsert (catalog)
  • tabcolarr
  • edit_selector
  • lineeditsubmit
  • pagination
  • paginationsize
  • paginationalways
  • paginationtemplate
  • paginationtemplatebtn
  • paginationscale

k8form:

  • templatetype
  • fields
  • container
  • html

html:

Indexing of the datadefinition:

  • numeric: >200 for personel use
  • string, example: "components" folder in your project folder

By nurmeric definitions the html files must be readed in the datadefintion file and added manually to the data definition.

String or alphanumeric definitions correspond to an folder in your project. the html files are automatically added to your data definition.

K8 Forms, Jsonform or a HTML form depend on the masterdata.formmode:

  • 1: html
  • 2: jsonform (default)
  • 3: k8form

Attention Json, please regard to enclose your collection keys in quotes. So you can easily check your json datastructure in jsonlint!

Naming conventions for HTML files

Naming Conventions
<object>_<purpose>_<sub name>_<type>datadefinition
components_catalog_container.htmlhtml.catalog.container
components_catalog_record.htmlhtml.catalog.record
documents_masterdata_items_container.htmlk8forms.html.items_container
documents_masterdata_items_record.htmljs_rec_records.items

Designation:

  • object
  • purpose
  • sub name (optional)
  • type

TCPDF and JsonPDF

JsonPDF is based on TCPDF. Its an easy Report Generator for documents like invoices.

Data structure: Invoice

here you can change the data:

JsonPDF definition (example: Invoice)

here you can change the definition:

Data structure overview

  • pdf.author
  • pdf.title
  • data[]
    • docnumber
    • addressblock
    • ...
    • items[]
      • position
      • number
      • text1
      • quantity
      • price
    • total
  • translate[] array with label translation
  • fields for page header and footer
  • more fields ...
  • as much as you need ...

JsonPDF definition structure

this areas are supported:

  • page
  • pageheader
  • areas with page margins
    • reportheader
    • detail
    • reportfooter
  • pagefooter

All positions (top, left) are relativ position to the parent position.

page properties

This are the supported properties:

  • top (margin)
  • left (margin)
  • width (or you set right)
  • height (or you set bottom)
  • right (margin)
  • bottom (margin)
  • orientation, default=P (Portrait), L=Landscape
  • unit, default=mm
  • format, default=A4

Output a PDF with PHP

Output by data_accessclass

ProcessData.php is called to create a PDF with the desired data. The parameters are (with examples):

  • process_action=PDF
  • datadefID=3
  • 1 of this:
    • keyvalue=13
    • clause=docID=13
  • jsonfile=myinvoice_definition.json
  • filename=Invoice-0815.PDF
  • dest=I (send PDF to browser)

The data access class checks the rights to read the data. The following function creates the PDF:

o->bpreparePDF($jsonfile,$clause,$dest,$filename)

JavaScript, create PDF by data_accessclass

Send PDF by email

PDF and email are created by PHP. Ajax starting the function like this:

Create PDF by data and JsonPDF definition

The JsonPDF definition and the data is send by Ajax to the server:

page elements, fieldtypes

This are the supported fieldtypes:

  • 109: Panel
  • 110: Cell fixed size
  • 111: Cell enlargeable
  • 112: Line
  • 114: Image
  • 115: Svg
  • 116: Panel with data structure
  • 117: WriteHTML

All positions (top, left) are relativ position to the parent position.

109, Panel properties

Properties:

  • enabled: 0/1
  • visibleeval: <PHP expression with placeholder>
    {{serviceprint}}==1
  • top
  • left
  • subs[]
  • only working well, if fixed width and height:
    • border
    • backgroundcolor

110, Cell fixed size properties

This are the supported properties:

  • enabled: 0/1
  • visibleeval
  • top
  • left
  • width
  • height
  • fieldname
  • label
  • labelwidth
  • mycolumn, column of your data
  • specification: clipwidth=1 !!$link
  • border, 0,1,"T","R","B,"L", one or all letters
  • bordercolor, default: "#FFFFFF"
  • backgroundcolor, example: "#E8E8E8"
  • fontfamily, default PDF_FONT_NAME_MAIN, helvetica
  • fontstyle, (string) empty: regular, B: bold, I: italic, U: underline, D: line trough, O: overline
  • fontsize, default 12, in points
  • fontcolor, default: "#FFFFFF"
  • alignement, string: L,C,R,J
  • datatype, 1:decimal, 4:date
  • decimals, 1,2,3,...

111, Cell enlargeable additional properties

This are the supported properties:

  • enlargeable
  • shrinkable

112, Line properties

This are the supported properties:

  • enabled: 0/1
  • visibleeval
  • top
  • left
  • width
  • height
  • bordercolor
  • style look here

114, Image properties

Only "JPG" is allowed. This are the supported properties:

  • enabled: 0/1
  • visibleeval
  • top
  • left
  • width
  • height
  • specification, link=http://tom24.info/webkit&linkfield=mylink&palign=L
  • label, src for image
  • mycolumn, src for image

115, Svg properties

  • enabled: 0/1
  • visibleeval
  • top
  • left
  • specification, imagescale=1&link=http://...
  • border
  • mycolumn

116, Panel with datastructure properties

  • enlargeable
  • shrinkable ?
  • enabled: 0/1
  • visibleeval
  • top
  • left
  • spceification: name of data structure
  • subs
    • reportheader
      • pageheaderoffset:0, if isset it will be added with its offset to the pageheader
    • detail
    • reportfooter

117, WriteHTML

  • enlargeable
  • shrinkable
  • enabled: 0/1
  • visibleeval
  • top
  • left
  • label
  • mycolumn

k8-CSS

k8-flex-table

Bootstrap Input Basics

  • label and input height: 34px
  • input padding: 6px 12px
  • label .control-label padding-top: 7px
  • font-size: 14px;
  • distance between lines: margin-bottom: 15px

k8-table Basics

  • label and input height: 34px
  • input padding: 6px 6px
  • label k8-label-table, padding: 7px 6px
  • font-size: 14px;
  • distance between lines: margin-bottom: 0px

horizontal Lines are made with:

  • k8-border (all 4 sides)
  • k8-border-top
  • k8-border-right
  • k8-border-bottom
  • k8-border-left
  • k8-border-u (3 sides)
  • k8-border-n (3 sides)

vertical Lines are made with:

  • .k8-flex-table-head > div

Example contacts

For table formatting "k8-flex-table" is used, its based on "display:flex".

Contacts

My footline

HTML

CSS

Backend

BasicFuncitons.php

Here are useful functions for:

  • data access
  • local support
  • generation datadefinition

Transfer datadefinition to JavaScript

only HTML-Snippets in page

datadefinition in page

datadefinition with Ajax

Change query string in JavaScript / jQuery

Even with JavaScript the page has to be reloaded:

php methods and data access

datadefinitions.php

For the basic datadefintion have a look to Master data.

The datadefinition contains the html frontend and refers the php classes of the object. In the website you have to add stylesheet and javascript and load the object.

Example for object datadefintion[x]:

  • rightcheck
  • json/form html container
    ['jsonform']['form'][1]['value']=gsread_file('object_invoice_container.html')
  • masterdata
    • save_mode=1
    • record=!!!
    • rightuser_create=true/false
    • placeholder_mode:
      • 0=placeholder
      • 1=[placeholder] default actual
      • 2={{placeholder}} future default
      • 3=[placeholder*] and {{placeholder*}} for data-loop_object
    • rights
      • create
        • 0:public=1
        • 1:admin=1
        • 2:superuser=2
        • 3:member=3
      • read
        ...
      • update
      • delete
  • childs, array for child tables
    • child table definition 1
      • child table definition 1.1
      • child table definition 1.2
    • child table definition 2
  • js_rec_record
    • objectname 1: html template 1
    • objectname 2: html template 2

the configuration of the data access class with child classes:

Each of my tables has 1 primary key. The table, the key and the data class are the most important terms. The "child" array can contain any number of children and can be nested. Additional you must set the master key, the column which contains the parentkey. Rightmode=3 turns off the right checking in the child table. fieldname is the column name of the array.

class_data_accessclass.php

Basic for the data access class are the following properties of the datadefintion:

  • rightcheck
  • table
  • key
  • objectclass
  • requiredfile
  • columns
    • Field
    • Type
    • fieldname
    • mytype
    • noupdate
    • noinsert
    • default
    • required
  • masterdata
    • rights
    • include
    • upload
    • sql_derived
    • sql_statement
    • sql_orderby
    • include (to extend the standard functions, you can include php snippets)
      • validate: filename
  • backend
    • foreignkeys
  • childs

The data access class support child classes. For each child in the datadefintion a new child class object is declared.

The data access class has the following methods:

  • __construct($datadefinition)
  • init()
  • bexist($ID)
  • bload($ID)
  • getEntries($clause)
  • bvalidate($postfields)
  • save()
  • add()
  • update()
  • delete($ID)
  • bpreparePDF($jsonfile,$clause='',$dest='I',&$filename='',$bmodel=0)
  • bcheckMaster(...)
  • nextnumber($colnumber,$clause,$default,$format="####",$increment=1)

Extend the data access class:

  • class <your class> extends data_accessclass
    • add new own functions to the class
  • includes
    • getEntries_sql
    • getEntries
    • validate
    • beforeinsert
    • afterinsert
    • beforeupdate
    • afterupdate
    • beforedelete
    • childdelete
    • afterdelete
__construct($datadefinition)

function flow:

  • prepare the necessay variables
  • init the rights
  • image support?
  • prepare the child classes
  • fill the include array
bload($ID)

getEntries($clause='',$orderby='',$psort='')

function flow:

  • $_SESSION[roles]
  • rightcheck
  • datamode
  • rights
  • masterdatadefID
  • table
  • sql_statement
  • sql_dervied
  • sql_orderby
  • baddimage
  • childs
  • parentcolumn
  • treearrayname
  • $_REQUEST
    • mytable_offset
    • mytable_limit, only if mytable_offset is set, mytable_limit is set, mytable_limit=-1 it's not set.
bvalidate(..)

function flow:

  • $_POST -> $this->postfields
  • check input fields against table columns
  • check required fields
  • $this->include['validate']
  • check childs
delete($ID)
  • check permission
  • check foreign keys
  • delete children
  • delete files
  • delete record
check permission

The data access rules are defined in the datadefnition: masterdata.rights. Without permission the delition is cancelled and error message is returned.

check foreign keys

datadefinition, example for table k8components

Before the deletion is excecuted the existens of the record in the foreign tables is checked! If it exist the deletion is cancelled and an error message is returned.

check foreign key by deviating column

datadefinition, example for table k8companyemployees

Deleting of the employee is avoided, when he already created a record in the k8componentstable. With "deleteloadrecord=true" the record is loaded. The column userID should be checked in the table k8components. In k8companyemployees the Primary Key is not important for this. The necessary column is defined like this: "sparekey":"userID". In k8components it correspond to the column: "creatorID".

validation

gbcheckinputcol($colobject,$postfields,&$error,$exeptions='',$labels='')

ProcessData.php

All ajax requests are send to "ProcessData.php".

Parameter:

  • process_action
  • datadefID
  • filters
  • clause
  • keyvalue
  • arr
  • prefix

ProcessData.php contains the following methods:

  • GetObject
    • return Json:
      • bok
      • data
      • error
  • ReadFilter
    • return Json:
      • array with records
  • (getRecords)
    • return Json:
      • array with records
  • Init
  • Load
    • return Json:
      • bok
      • error
      • dat, (record)
  • Save
    • return Json:
      • bok
      • error
      • dat, (record)
  • Delete
    • return Json:
      • bok: 0 or ID of deleted record
      • error
  • Sort

data access rights

Access rights can only be granted by using login and php sessions. The access check is activated for an object in the datadefinition by setting "rightcheck=1". In the data table the column "creatorID" is added. Each user can be member in 1 or more roles. By opening the website the user is assigned to the role "0" (public). By login the role public is replaced by the roles in the login table: k8login.roles="3,5". For each object or table, for each CRUD operation (create, read, update, delete) and role an access check is implemented.

This is the data access definition in the datadefinition (masterdata.rights):

  • CRUD Operation
    • Role ID
      • Access check

CRUD Operation, SQL methods
OperationSQL commandReturn values
CreateINSERT true / false
ReadSELECT join
clause
condition for rightuser_update: true/false
condition for rightuser_delete: true/false
UpdateUPDATEtrue / false
DeleteDELETEtrue / false
Roles
IDRoleComment
0publicuser not logged in
1adminall rights in a client
2superuserall rights in the table / object
3memberlogged in user
5friendsassigned in table: k8loginfriends
xotherscreate by yourself
Access check
NumberCheck method
0no rights
1access permission in this client: table.clientID=$_SESSION[clientID]
2permission granted
3user logged in: $_SESSION[userID]<>0
10table.creatorID=$_SESSION[userID]
11check friend k8loginfriends.friendID=$_SESSION[userID]
1000check parent table access rights
...programm your own check

By each CRUD operation the rights are checked. If the operation is by Create, Update or Delete is not granted, an error is returned. Reading a table can return an empty recordset, because of the missing rights.

By Read the results of the access check for Update and Delete are returned in advance like this:

  • in the datadefinitition:
    • masterdata.rightuser_create: true
  • by reading the recordset:
    • rightuser_update: true
    • rightuser_delete: true

To check the user right by foreign tables the table can be joined or checked by "EXISTS":


Default Rights

This are the default rights in the data access class (masterdata.defaultrights=true (default)).

access matrix, cell number=Access check
Operation0:public1:admin2:superuser3:member
Create0121
Read01210
Update01210
Delete01210

Rights from the datadefinition overwrite it. To allow the roles: public and member to read all records in the object, add in the datadefinition:

access rights by master

please set the following properties;

  • masterkey
  • masterdatadefID

The access rights depend on the master record. If the master record grant update rights, "create, update, delete" rights are granted on the child records.

Working with include

The datadefinition "masterdata":