Editor PHP 2.0.0

Editor extends Ext

DataTables Editor base class for creating editable tables.

Editor class instances are capable of servicing all of the requests that DataTables and Editor will make from the client-side - specifically:

  • Get data
  • Create new record
  • Edit existing record
  • Delete existing records

The Editor instance is configured with information regarding the database table fields that you wish to make editable, and other information needed to read and write to the database (table name for example!).

This documentation is very much focused on describing the API presented by these DataTables Editor classes. For a more general overview of how the Editor class is used, and how to install Editor on your server, please refer to the Editor manual.

Tags
example

very basic example of using Editor to create a table with four fields. This is all that is needed on the server-side to create a editable table - the {@see Editor->process()} method determines what action DataTables / Editor is requesting from the server-side and will correctly action it.

  Editor::inst( $db, 'browsers' )
      ->fields(
          Field::inst( 'first_name' )->validator( Validate::required() ),
          Field::inst( 'last_name' )->validator( Validate::required() ),
          Field::inst( 'country' ),
          Field::inst( 'details' )
      )
      ->process( $_POST )
      ->json();

Table of Contents

ACTION_CREATE  = 'create'
Request type - create
ACTION_DELETE  = 'remove'
Request type - delete
ACTION_EDIT  = 'edit'
Request type - edit
ACTION_READ  = 'read'
Request type - read
ACTION_UPLOAD  = 'upload'
Request type - upload
$version  : string
__construct()  : mixed
Constructor.
_ssp_field()  : mixed
Convert a column index to a database field name - used for server-side processing requests.
action()  : string
Determine the request type from an HTTP request.
actionName()  : string|self
Get / set the action name to read in HTTP parameters. This can be useful to set if you are using a framework that uses the default name of `action` for something else (e.g. WordPress).
data()  : array<string|int, mixed>
Get the data constructed in this instance.
db()  : Database|self
Get / set the DB connection instance
debug()  : mixed
Get / set debug mode and set a debug message.
field()  : mixed
Get / set field instance.
fields()  : mixed
Get / set field instances.
idPrefix()  : mixed
Get / set the DOM prefix.
inData()  : mixed
Get the data that is being processed by the Editor instance. This is only useful once the `process()` method has been called, and is available for use in validation and formatter methods.
inst()  : Editor|Field|Join|Upload
Static method to instantiate a new instance of a class (shorthand of 'instantiate').
instantiate()  : Editor|Field|Join|Upload
Static method to instantiate a new instance of a class.
join()  : mixed
Get / set join instances. Note that for the majority of use cases you will want to use the `leftJoin()` method. It is significantly easier to use if you are just doing a simple left join!
json()  : mixed
Get the JSON for the data constructed in this instance.
jsonp()  : self
Echo out JSONP for the data constructed and processed in this instance.
leftJoin()  : self
Add a left join condition to the Editor instance, allowing it to operate over multiple tables. Multiple `leftJoin()` calls can be made for a single Editor instance to join multiple tables.
leftJoinRemove()  : mixed
Indicate if a remove should be performed on left joined tables when deleting from the parent row. Note that this is disabled by default and will be removed completely in v2. Use `ON DELETE CASCADE` in your database instead.
on()  : self
Add an event listener. The `Editor` class will trigger an number of events that some action can be taken on.
pkey()  : mixed
Get / set the primary key.
pkeyToArray()  : array<string|int, mixed>
Convert a primary key combined value to an array of field values.
pkeyToValue()  : string
Convert a primary key array of field values to a combined value.
process()  : self
Process a request from the Editor client-side to get / set data.
readTable()  : array<string|int, string>|self
The CRUD read table name. If this method is used, Editor will create from the table name(s) given rather than those given by `Editor->table()`. This can be a useful distinction to allow a read from a VIEW (which could make use of a complex SELECT) while writing to a different table.
table()  : mixed
Get / set the table name.
transaction()  : mixed
Get / set transaction support.
tryCatch()  : bool|Editor
Enable / try catch when `process()` is called. Disabling this can be useful for debugging, but is not recommended for production.
validate()  : mixed
Perform validation on a data set.
validator()  : Editor|callable
Get / set a global validator that will be triggered for the create, edit and remove actions performed from the client-side. Multiple validators can be added.
where()  : array<string|int, string>|self
Where condition to add to the query used to get data from the database.
whereSet()  : bool
Get / set if the WHERE conditions should be included in the create and edit actions.
write()  : mixed
_getSet()  : mixed
Common getter / setter function for DataTables classes.
_propExists()  : bool
Determine if a property is available in a data set (allowing `null` to be a valid value)
_readProp()  : mixed
Read a value from a data structure, using Javascript dotted object notation. This is the inverse of the `_writeProp` method and provides the same support, matching DataTables' ability to read nested JSON data objects.
_writeProp()  : mixed
Write the field's value to an array structure, using Javascript dotted object notation to indicate JSON data structure. For example `name.first` gives the data structure: `name: { first: ... }`. This matches DataTables own ability to do this on the client-side, although this doesn't implement implement quite such a complex structure (no array / function support).

Constants

ACTION_CREATE

Request type - create

public mixed ACTION_CREATE = 'create'

ACTION_DELETE

Request type - delete

public mixed ACTION_DELETE = 'remove'

ACTION_EDIT

Request type - edit

public mixed ACTION_EDIT = 'edit'

ACTION_READ

Request type - read

public mixed ACTION_READ = 'read'

ACTION_UPLOAD

Request type - upload

public mixed ACTION_UPLOAD = 'upload'

Properties

$version

public string $version = '2.0.0'

Methods

__construct()

Constructor.

public __construct([mixed $db = null ][, string|array<string|int, mixed> $table = null ][, mixed $pkey = null ]) : mixed

@param Database $db An instance of the DataTables Database class that we can use for the DB connection. Can be given here or with the 'db' method.

Parameters
$db : mixed = null
$table : string|array<string|int, mixed> = null

The table name in the database to read and write information from and to. Can be given here or with the 'table' method. @param string|array $pkey Primary key column name in the table given in the $table parameter. Can be given here or with the 'pkey' method.

$pkey : mixed = null
Return values
mixed

_ssp_field()

Convert a column index to a database field name - used for server-side processing requests.

public _ssp_field(mixed $http, int $index) : mixed

@param array $http HTTP variables (i.e. GET or POST)

Parameters
$http : mixed
$index : int

Index in the DataTables' submitted data @returns string DB field name @throws \Exception Unknown fields @private Note that it is actually public for PHP 5.3 - thread 39810

Return values
mixed

action()

Determine the request type from an HTTP request.

public static action(array<string|int, mixed> $http[, string $name = 'action' ]) : string
Parameters
$http : array<string|int, mixed>

Typically $_POST, but can be any array used to carry an Editor payload

$name : string = 'action'

The parameter name that the action should be read from.

Return values
string

Editor::ACTION_READ, Editor::ACTION_CREATE, Editor::ACTION_EDIT or Editor::ACTION_DELETE indicating the request type.

actionName()

Get / set the action name to read in HTTP parameters. This can be useful to set if you are using a framework that uses the default name of `action` for something else (e.g. WordPress).

public actionName([mixed $_ = null ]) : string|self

@param string Value to set. If not given, then used as a getter.

Parameters
$_ : mixed = null
Return values
string|self

Value, or self if used as a setter.

data()

Get the data constructed in this instance.

public data() : array<string|int, mixed>

This will get the PHP array of data that has been constructed for the command that has been processed by this instance. Therefore only useful after process has been called.

Return values
array<string|int, mixed>

Processed data array.

db()

Get / set the DB connection instance

public db([mixed $_ = null ]) : Database|self

@param Database $_ DataTable's Database class instance to use for database connectivity. If not given, then used as a getter.

Parameters
$_ : mixed = null
Return values
Database|self

The Database connection instance if no parameter is given, or self if used as a setter.

debug()

Get / set debug mode and set a debug message.

public debug([bool|mixed $_ = null ][, mixed $path = null ]) : mixed

It can be useful to see the SQL statements that Editor is using. This method enables that ability. Information about the queries used is automatically added to the output data array / JSON under the property name debugSql.

This method can also be called with a string parameter, which will be added to the debug information sent back to the client-side. This can be useful when debugging event listeners, etc.

Parameters
$_ : bool|mixed = null

Debug mode state. If not given, then used as a getter. If given as anything other than a boolean, it will be added to the debug information sent back to the client. @param string [$path=null] Set an output path to log debug information @return boolean|self Debug mode state if no parameter is given, or self if used as a setter or when adding a debug message.

$path : mixed = null
Return values
mixed

field()

Get / set field instance.

public field([mixed $_ = null ]) : mixed

The list of fields designates which columns in the table that Editor will work with (both get and set).

Parameters
$_ : mixed = null
Return values
mixed

fields()

Get / set field instances.

public fields([mixed $_ = null ]) : mixed

An alias of field, for convenience.

Parameters
$_ : mixed = null
Return values
mixed

idPrefix()

Get / set the DOM prefix.

public idPrefix([string $_ = null ]) : mixed

Typically primary keys are numeric and this is not a valid ID value in an HTML document - is also increases the likelihood of an ID clash if multiple tables are used on a single page. As such, a prefix is assigned to the primary key value for each row, and this is used as the DOM ID, so Editor can track individual rows.

Parameters
$_ : string = null

Primary key's name. If not given, then used as a getter. @return string|self Primary key value if no parameter is given, or self if used as a setter.

Return values
mixed

inData()

Get the data that is being processed by the Editor instance. This is only useful once the `process()` method has been called, and is available for use in validation and formatter methods.

public inData() : mixed

@return array Data given to process().

Return values
mixed

inst()

Static method to instantiate a new instance of a class (shorthand of 'instantiate').

public static inst() : Editor|Field|Join|Upload

This method performs exactly the same actions as the 'instantiate' static method, but is simply shorter and easier to type!

Return values
Editor|Field|Join|Upload

class @static

instantiate()

Static method to instantiate a new instance of a class.

public static instantiate() : Editor|Field|Join|Upload

A factory method that will create a new instance of the class that has extended 'Ext'. This allows classes to be instantiated and then chained - which otherwise isn't available until PHP 5.4. If using PHP 5.4 or later, simply create a 'new' instance of the target class and chain methods as normal.

Return values
Editor|Field|Join|Upload

Instantiated class @static

join()

Get / set join instances. Note that for the majority of use cases you will want to use the `leftJoin()` method. It is significantly easier to use if you are just doing a simple left join!

public join([mixed $_ = null ]) : mixed

The list of Join instances that Editor will join the parent table to (i.e. the one that the Editor->table() and Editor->fields methods refer to in this class instance).

Parameters
$_ : mixed = null
Return values
mixed

json()

Get the JSON for the data constructed in this instance.

public json([bool $print = true ], mixed $options) : mixed

Basically the same as the Editor->data() method, but in this case we echo, or return the JSON string of the data.

Parameters
$print : bool = true

Echo the JSON string out (true, default) or return it (false). @param int JSON encode option https://www.php.net/manual/en/json.constants.php @return string|self self if printing the JSON, or JSON representation of the processed data if false is given as the first parameter.

$options : mixed
Return values
mixed

jsonp()

Echo out JSONP for the data constructed and processed in this instance.

public jsonp([string $callback = null ]) : self

This is basically the same as Editor->json() but wraps the return in a JSONP callback.

Parameters
$callback : string = null

The callback function name to use. If not given or null, then $_GET['callback'] is used (the jQuery default).

Tags
throws
Exception

JSONP function name validation

Return values
self

Self for chaining.

leftJoin()

Add a left join condition to the Editor instance, allowing it to operate over multiple tables. Multiple `leftJoin()` calls can be made for a single Editor instance to join multiple tables.

public leftJoin(string $table, string $field1[, string $operator = null ][, string $field2 = null ]) : self

A left join is the most common type of join that is used with Editor so this method is provided to make its use very easy to configure. Its parameters are basically the same as writing an SQL left join statement, but in this case Editor will handle the create, update and remove requirements of the join for you:

  • Create - On create Editor will insert the data into the primary table and then into the joined tables - selecting the required data for each table.
  • Edit - On edit Editor will update the main table, and then either update the existing rows in the joined table that match the join and edit conditions, or insert a new row into the joined table if required.
  • Remove - On delete Editor will remove the main row and then loop over each of the joined tables and remove the joined data matching the join link from the main table.

Please note that when using join tables, Editor requires that you fully qualify each field with the field's table name. SQL can result table names for ambiguous field names, but for Editor to provide its full CRUD options, the table name must also be given. For example the field first_name in the table users would be given as users.first_name.

Parameters
$table : string

Table name to do a join onto

$field1 : string

Field from the parent table to use as the join link

$operator : string = null

Join condition (=, '<`, etc)

$field2 : string = null

Field from the child table to use as the join link

Tags
example

join:

    ->field(
      Field::inst( 'users.first_name as myField' ),
      Field::inst( 'users.last_name' ),
      Field::inst( 'users.dept_id' ),
      Field::inst( 'dept.name' )
    )
    ->leftJoin( 'dept', 'users.dept_id', '=', 'dept.id' )
    ->process($_POST)
    ->json();
```</code>```

This is basically the same as the following SQL statement:

```sql
  SELECT users.first_name, users.last_name, user.dept_id, dept.name
  FROM users
  LEFT JOIN dept ON users.dept_id = dept.id
Return values
self

Self for chaining.

leftJoinRemove()

Indicate if a remove should be performed on left joined tables when deleting from the parent row. Note that this is disabled by default and will be removed completely in v2. Use `ON DELETE CASCADE` in your database instead.

public leftJoinRemove([bool $_ = null ]) : mixed

@deprecated

Parameters
$_ : bool = null

Value to set. If not given, then used as a getter. @return boolean|self Value if no parameter is given, or self if used as a setter.

Return values
mixed

on()

Add an event listener. The `Editor` class will trigger an number of events that some action can be taken on.

public on(string $name, callable $callback) : self
Parameters
$name : string

Event name

$callback : callable

Callback function to execute when the event occurs

Return values
self

Self for chaining.

pkey()

Get / set the primary key.

public pkey([string|array<string|int, mixed> $_ = null ]) : mixed

The primary key must be known to Editor so it will know which rows are being edited / deleted upon those actions. The default value is ['id'].

Parameters
$_ : string|array<string|int, mixed> = null

Primary key's name. If not given, then used as a getter. An array of column names can be given to allow composite keys to be used. @return string|self Primary key value if no parameter is given, or self if used as a setter.

Return values
mixed

pkeyToArray()

Convert a primary key combined value to an array of field values.

public pkeyToArray(string $value[, bool $flat = false ][, array<string|int, string> $pkey = null ]) : array<string|int, mixed>
Parameters
$value : string

The id that should be split apart

$flat : bool = false

Flag to indicate if the returned array should be flat (useful for where conditions) or nested for join tables.

$pkey : array<string|int, string> = null

The primary key name - will use the instance value if not given

Tags
throws
Exception

If the primary key value does not match the expected length based on the primary key configuration, an exception will be thrown.

Return values
array<string|int, mixed>

Array of field values that the id was made up of.

pkeyToValue()

Convert a primary key array of field values to a combined value.

public pkeyToValue(string $row[, bool $flat = false ]) : string
Parameters
$row : string

The row of data that the primary key value should be extracted from.

$flat : bool = false

Flag to indicate if the given array is flat (useful for where conditions) or nested for join tables.

Tags
throws
Exception

If one of the values that the primary key is made up of cannot be found in the data set given, an Exception will be thrown.

Return values
string

The created primary key value.

process()

Process a request from the Editor client-side to get / set data.

public process(mixed $data) : self

@param array $data Typically $_POST or $_GET as required by what is sent by Editor

Parameters
$data : mixed
Return values
self

readTable()

The CRUD read table name. If this method is used, Editor will create from the table name(s) given rather than those given by `Editor->table()`. This can be a useful distinction to allow a read from a VIEW (which could make use of a complex SELECT) while writing to a different table.

public readTable([mixed $_ = null ]) : array<string|int, string>|self

@param string|array $_,... Read table names given as a single string, an array of strings or multiple string parameters for the function.

Parameters
$_ : mixed = null
Return values
array<string|int, string>|self

Array of read tables names, or self if used as a setter.

table()

Get / set the table name.

public table([mixed $_ = null ]) : mixed

The table name designated which DB table Editor will use as its data source for working with the database. Table names can be given with an alias, which can be used to simplify larger table names. The field names would also need to reflect the alias, just like an SQL query. For example: users as a.

Parameters
$_ : mixed = null
Return values
mixed

transaction()

Get / set transaction support.

public transaction([bool $_ = null ]) : mixed

When enabled (which it is by default) Editor will use an SQL transaction to ensure data integrity while it is performing operations on the table. This can be optionally disabled using this method, if required by your database configuration.

Parameters
$_ : bool = null

Enable (true) or disabled (false) transactions. If not given, then used as a getter. @return boolean|self Transactions enabled flag, or self if used as a setter.

Return values
mixed

tryCatch()

Enable / try catch when `process()` is called. Disabling this can be useful for debugging, but is not recommended for production.

public tryCatch([bool $_ = null ]) : bool|Editor
Parameters
$_ : bool = null

true to enable (default), otherwise false to disable

Return values
bool|Editor

Value if used as a getter, otherwise $this when used as a setter.

validate()

Perform validation on a data set.

public validate(array<string|int, mixed> &$errors, mixed $data) : mixed

Note that validation is performed on data only when the action is create or edit. Additionally, validation is performed on the wire data - i.e. that which is submitted from the client, without formatting. Any formatting required by setFormatter is performed after the data from the client has been validated.

Parameters
$errors : array<string|int, mixed>

Output array to which field error information will be written. Each element in the array represents a field in an error condition. These elements are themselves arrays with two properties set; name and status. @param array $data The format data to check @return boolean true if the data is valid, false if not.

$data : mixed
Return values
mixed

validator()

Get / set a global validator that will be triggered for the create, edit and remove actions performed from the client-side. Multiple validators can be added.

public validator([callable $_ = null ]) : Editor|callable
Parameters
$_ : callable = null

Function to execute when validating the input data. It is passed three parameters: 1. The editor instance, 2. The action and 3. The values.

Return values
Editor|callable

Editor instance if called as a setter, or the validator function if not.

where()

Where condition to add to the query used to get data from the database.

public where([string|callable $key = null ][, string $value = null ][, string $op = '=' ]) : array<string|int, string>|self

Can be used in two different ways:

  • Simple case: where( field, value, operator )
  • Complex: where( fn )

The simple case is fairly self explanatory, a condition is applied to the data that looks like field operator value (e.g. name = 'Allan'). The complex case allows full control over the query conditions by providing a closure function that has access to the database Query that Editor is using, so you can use the where(), or_where(), and_where() and where_group() methods as you require.

Please be very careful when using this method! If an edit made by a user using Editor removes the row from the where condition, the result is undefined (since Editor expects the row to still be available, but the condition removes it from the result set).

Parameters
$key : string|callable = null

Single field name or a closure function

$value : string = null

Single field value.

$op : string = '='

Condition operator: <, >, = etc

Return values
array<string|int, string>|self

Where condition array, or self if used as a setter.

whereSet()

Get / set if the WHERE conditions should be included in the create and edit actions.

public whereSet([mixed $_ = null ]) : bool

@param boolean $_ Include (true), or not (false)

Parameters
$_ : mixed = null
Return values
bool

Current value @deprecated Note that whereSet is now deprecated and replaced with the ability to set values for columns on create and edit. The C# libraries do not support this option at all.

write()

public write([mixed $_writeVal = null ]) : mixed
Parameters
$_writeVal : mixed = null
Return values
mixed

_getSet()

Common getter / setter function for DataTables classes.

protected _getSet(mixed &$prop, mixed $val[, mixed $array = false ]) : mixed

This getter / setter method makes building getter / setting methods easier, by abstracting everything to a single function call.

Parameters
$prop : mixed

The property to set @param mixed $val The value to set - if given as null, then we assume that the function is being used as a getter. @param boolean $array Treat the target property as an array or not (default false). If used as an array, then values passed in are added to the $prop array. @return self|mixed Class instance if setting (allowing chaining), or the value requested if getting.

$val : mixed
$array : mixed = false
Return values
mixed

_propExists()

Determine if a property is available in a data set (allowing `null` to be a valid value)

protected _propExists(string $name, array<string|int, mixed> $data) : bool
Parameters
$name : string

Javascript dotted object name to write to

$data : array<string|int, mixed>

Data source array to read from

Tags
private
Return values
bool

true if present, false otherwise

_readProp()

Read a value from a data structure, using Javascript dotted object notation. This is the inverse of the `_writeProp` method and provides the same support, matching DataTables' ability to read nested JSON data objects.

protected _readProp(string $name, array<string|int, mixed> $data) : mixed
Parameters
$name : string

Javascript dotted object name to write to

$data : array<string|int, mixed>

Data source array to read from

Tags
private
Return values
mixed

The read value, or null if no value found.

_writeProp()

Write the field's value to an array structure, using Javascript dotted object notation to indicate JSON data structure. For example `name.first` gives the data structure: `name: { first: ... }`. This matches DataTables own ability to do this on the client-side, although this doesn't implement implement quite such a complex structure (no array / function support).

protected _writeProp(array<string|int, mixed> &$out, string $name, mixed $value) : mixed
Parameters
$out : array<string|int, mixed>

Array to write the data to

$name : string

Javascript dotted object name to write to

$value : mixed

Value to write

Tags
throws
Exception

Information about duplicate properties

private
Return values
mixed

Search results