Autogenerated Views

From Cloudrexx Development Wiki
Jump to: navigation, search

Introduction

Cloudrexx can automatically generate the view layer based on models. Suppored models are Doctrine entities or array-data (wrapped in \Cx\Core_Modules\Listing\Model\Entity\DataSet). The autogenerated views provided by \Cx\Core\Html\Controller\ViewGenerator are:

View Name Purpose
list Overview List all entities in form of a table
form Detail view Add, edit or copy form of an entity
show Experimental Readonly view Display of a single entity

Aside from the autogenerated views, \Cx\Core\Html\Controller\ViewGenerator does also handle the interaction like create, edit, copy, delete, sort, filter and more with the rendering entities. Further, it also supports the handling of relations to associated entities. The latter is limited to rendering entities of type Doctrine entity.

Create an autogenerated view

In Backend

\Cx\Core\Core\Model\Entity\SystemComponentBackendController automatically uses ViewGenerator to render pre-defined views which you can customize (see options below). This means you should not have to call ViewGenerator yourself.
SystemComponentBackendController needs the following code in the current template to be able to parse a view with ViewGenerator.

<!-- BEGIN entity_view --> 
{ENTITY_VIEW} 
<!-- END entity_view -->

You can pass options to these instances of ViewGenerator by overriding SystemComponentBackendController::getViewGeneratorOptions(). You may also override any of the following methods to gain more control over what gets rendered:

  • SystemComponentBackendController::getEntityClassesWithView()
    Use to register additional non-Doctrine entities that will be used in combination with SystemComponentBackendController::getViewGeneratorParseObjectForEntityClass() to render alternate entities.
  • SystemComponentBackendController::getViewGeneratorParseObjectForEntityClass()
    Use to change the rendering entity. Can be used to generate the autogenerated views of some other entity than the one identified by the backend section.
  • SystemComponentBackendController::parseEntityClassPage()
    Use to overwrite the default ViewGenerator initialization of default backend sections.

In any other case

If you want to use ViewGenerator in frontend or for any other use-case (like command-line, export, ...) you can use the following code to generate a view:

$view = new \Cx\Core\Html\Controller\ViewGenerator($renderObject, $vgOptions);
echo $view;

$renderObject can be any of the types described in Render object.

For $vgOptions, see the available options below.

Render object

The ViewGenerator accepts different types of data to render a view from:

  • A Doctrine entity class name (fully qualified). This will render a view for all entities of this class.
  • A single object
  • A list of objects
  • A DataSet instance
  • An array

All write functions (add, edit, delete) only work reliably if the render object is based on Doctrine. This is a known limitation that will be lifted in a later version.

Internally, all of the possibilities above are converted to a DataSet. The type of data is determined by DataSet::getDataType(). This leads to three cases:

  • A Doctrine entity or a list of them.
  • Any other type of object or a list of them.
  • A (potentially multi-dimensional) array which is not a simple list of objects. Further on we will call this type "array".

Options

If the object to be rendered is not of type array, then ViewGenerator expects the following structure:

$vgOptions = array(
    'FQCN\of\Entity' => $options,
);

If the object to be rendered is of type array then the format is as follows:

$vgOptions = array(
    'Cx\Core_Modules\Listing\Model\Entity\DataSet' => array(
        '<dataSetIdentifier>' => $options,
    ),
);

<dataSetIdentifier> is the identifier of the given DataSet instance. This defaults to . So if an array is passed to the ViewGenerator, use as the DataSet's identifier.

Note: In case the rendering entity has associations to other entities that shall get rendered to, then the rendering of those (associated) entities can be configured by specifying an additonal set of options identified by their FQCN. I.e.:

$vgOptions = array(
    'FQCN\of\Entity' => $options,
    'FQCN\of\associated\EntityA' => $options,
    'FQCN\of\associated\EntityB' => $options,
);

The following sections list all available options to be set through $options according to the specification above.

Root level options

These options can be set the following way:

$options[<option_name>] = <option_value>;
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
entityName string $_CORELANG['TXT_CORE_ENTITY'] Translated display name of the entity. This is used to customize several view texts.
header string (empty) [1] Title of the table if a table for overview. If it's set to an empty string the header row will be hidden.
cancelUrl \Cx\Core\Routing\Url Request URL URL used as jump-back on cancel
parsing array See Parsing (empty) Use to customize the parsing behaviour of the views.
preRenderDetail array
array(
    'adapter' => $name,
    'method' => $method,
)
(empty) Add custom HTML-code at the end of the detail (form) and readonly (show) view.

Set $name and $method to AdapterName and AdapterMethod of an exposed method.

Arguments passed to exposed method are as follows:

Argument Datatype Description
viewGenerator \Cx\Core\Html\Controller\ViewGenerator The rendering ViewGenerator instance.
formGenerator \Cx\Core\Html\Controller\FormGenerator The rendering FormGenerator instance used for the detail (form) and readonly (show) view.
entityId mixed The identifier of the rendering entity. Either an integer or an array (if the identifier is a composite key)

Exposed method must return the HTML-code (as string or magically castable to string) that shall be added at the end of the detail (form) or readonly (show) view.

Note: The exposed method is being called before the detail (form) or readonly (show) view is being rendered.
rowAttributes array
array(
    'adapter' => $name,
    'method' => $method,
)
(empty) Customize row attributes (HTML attributes of all <tr> elements) of overview view (list).

Set $name and $method to AdapterName and AdapterMethod of an exposed method.

Arguments passed to exposed method are as follows:

Argument Datatype Description
data array Associated list of all properties of the rendering entity (of the parsing row).
Note: Is set to an empty array for the first (-> header) row.
attributes array Associated list of already set HTML attributes (of the parsing row)

Exposed method must return an associated array of all HTML attributes that shall be applied on the <tr> elements as follows:

array(
    '<html_attribute_name>' => '<value>',
    ...
)
showPrimaryKeys boolean false This is not implemented yet! Show the primary keys in the edit view.
template array See Template (empty) Use to load a different template to be used for parsing the views.
  1. BackendController::getViewGeneratorOptions() sets this to $_ARRAYLANG['TXT_<component_type>_<component_name>_ACT_<class_identifier>'] if this index is set.

Template

Use to load a different template to be used for parsing the views. Configure as follows:

$options['template'][<option_name>] = <option_value>;
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
table string filepath relative to the root directory of Cloudrexx core/Html/View/Template/Generic/Table.html Set template to be used for detail (form) and readonly (show) view.
tableView string filepath relative to the root directory of Cloudrexx core/Html/View/Template/Generic/TableView.html Set template to be used for the overview view (list).


Parsing

The parsing behaviour can be customized as follows:

$options['parsing'][<option_name>] = <option_value>;
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
showNA boolean true / false false Set to true to output None (for associations) or <empty> (for scalar properties) as cell content instead of leaving a cell empty.


Functions

A ViewGenerator can be customized and extended by several functions that can be set as follows:

$options['functions']['<option_name>'] = <option_value>;

All

Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
edit boolean true / false false [1] Whether editing existing entries is possible in this view.
add boolean true / false false [1] Whether adding new entries is possible in this view.
copy boolean true / false false [1] Whether copying of existing entries is possible in this view.
show boolean true / false false [1] Whether a readonly view can be shown.
delete boolean true / false false [1] Whether deleting existing entries is possible in this view.
order array See Ordering (empty) Set the order in which the entities shall be listed on the listing view.
sorting boolean true / false false [1] Enable interactive column sorting on the listing view.
sortBy array See Drag & Drop Sorting (empty) Enable drag & drop sorting on the listing view.
paging boolean true / false false [1] Whether paging is used if there are more entries than the configured page limit.
searching boolean true / false false Whether a search by term (OR-ed search over all fields) should be possible. Please note that all fields that should be included in that search need to be whitelisted (see field option "allowSearching").
filtering boolean true / false false Whether a search by field value ("extended search", AND-ed search over all fields) should be possible.
autoHideFiltering boolean true / false true Whether to hide filtering behind a "extended search" link if searching and filtering are active.
actions string / callback HTML code / function($rowData) (empty) Additional actions to display in the "functions" column.
Callback arguments are: $rowData, $editId
Important: Please note that $editId currently contains the complete GET argument "editid". This will be changed to an array with all (potentially composite) keys for this ViewGenerator instance.
formButtons boolean true / false true Whether to add submit and cancel buttons to forms. To integrate forms in surrounding content this can be set to false.
editable boolean true / false false Whether fields in the overview should be editable.
Important: The editable option must also be activated for the fields. See Field Options
alphabetical string field name (empty) If this is set to a field name a list of links with all letters in the alphabet is displayed.
status array See Status Toggling (empty) Enable a status toggling widget on one specified field.
export array See Export (empty) Enable CSV-export functionality.
filterCallback callback QueryBuilder (empty) Overrides the filter callback. (extended search)
Callback arguments are: $qb, $crit
searchCallback callback QueryBuilder (empty) Overrides the search callback. (search).
Callback arguments are: $qb, $fields, $crit
onclick array See Custom Delete Event (empty) Overwrite the JavaScript onclick event of the delete function on the listing view.
  1. 1.0 1.1 1.2 1.3 1.4 1.5 1.6 BackendController::getViewGeneratorOptions() sets this to true


Ordering

Use to define the order in which the entities shall be listed by default on the listing view. This will get overridden by the user's choice if column sorting or Drag'n'Drop sorting is active.

$options['functions']['order'] = array(
    '<fieldName>' => <sortOrder>,
);
  • Set <fieldName> to the field (of the rendering entity) by which the entries shall be ordered by.
  • Set <sortOrder> to either one of the PHP constants SORT_ASC or SORT_DESC.


Note: Multi-column ordering can be achieved by adding each $field to the array. The earlier a $field occurs in the array, the higher its precedence will be on the applied order. I.e.:
$options['functions']['order'] = array(
    '<fieldNameA>' => <sortOrder>,
    '<fieldNameB>' => <sortOrder>,
);

Column Sorting

Use to enable interactive column sorting on the listing view. Configure as follows:

$options['functions']['sorting'] = true;
Note: Individual columns can be excluded from interactive column sorting by setting their field option sorting to false.


Drag & Drop Sorting

Use to enable drag & drop sorting on the listing view. Configure as follows:

$options['functions']['sortBy'] = array(
    '<option_name>' => <option_value>,
);
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
field array array($field => $direction) (empty) Set $field to the field (of the rendering entity) that holds the current sorting order and shall be used to update the adjusted sorting order.
Restrictions
  • In case Ordering is enabled, then the Drag & Drop Sorting will only be enabled, if $field is set to the same value as <field_name> of function order.
  • In case Sorting is enabled, then the Drag & Drop Sorting will only be enabled, if the currently selected field (column) is the same as defined by $field.

$direction is used to define the order direction in which the initial listing by $field shall be done. Either set to SORT_ASC or SORT_DESC.

jsonadapter array array($name => $method) (empty) Overrides the default handler for updating the adjusted sort order (done through drag & drop).

Set $name and $method to AdapterName and AdapterMethod of an exposed method.

Example:

$options['functions']['sortBy']['field'] = array(
    'order_id' => SORT_ASC,
);

Status Toggling

Enable a status toggling widget on one specified field. These options can be set the following way:

$options['functions']['status'] = array(
    '<option_name>' => <option_value>,
);
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
field string $field (empty) Set $field to the field (of the rendering entity) that shall be used for the status toggling.
jsonadapter array array($name => $method) (empty) Overrides the default handler for toggling the status (0/1) of the specified field.

Set $name and $method to AdapterName and AdapterMethod of an exposed method.

Export

Enable a CSV-file-export. The default export handler will export the currently listed entities (based on filtering and search).

$options['functions']['export'] = array(
    '<option_name>' => <option_value>,
);

If $options['functions']['export'] is not set or set to anything other than an array, then the export function is disabled.

All following options are optional:

Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
jsonadapter array array($name => $method) (empty) Overrides the default handler for processing the export request.

Set $name and $method to AdapterName and AdapterMethod of an exposed method.

fieldList array List of fields (empty)
Upcoming feature. Not yet available.

Overrides the default list of fields / field order to export. By default all fields are exported in order of appearance.


Custom Delete Event

The JavaScript onclick event of the delete function can be overwritten the following way:

$options['functions']['onclick'] = array(
    'delete' => '<js_callback_function_name>',
);

Then implement the associated JavaScript function:

function <js_callback_function_name>(deleteUrl) {
    // Code
}

Tabs

By default, the detail view does list all fields (those configured to be displayed) at once.

However, the ViewGenerator provides also the ability to split the view up into multiple tabs. This can be achieved by using the option tabs as follows:

$options['tabs'] = array(
    '<tab_name>' => array(
        'fields' => <fieldlist>,
        'header' => '<tab_title>',
    ),
);
  • Set <tab_name> to a programmatic name for the tab.
  • For <fieldlist> set an array of all fields that shall be displayed in that particular tab.
    Note: Fields that are not assigned to any tab will be displayed in the default/overview tab.
  • Set <tab_title> to the literal text that shall be used as viewable tab title.
    Note: The header option is optional. If left out, the system will try to automatically load the text-variable $_ARRAYLANG['<tab_name>'] by default.
Note: The default/overview tab is being labelled as "General". This can be customized as follows:
$options['tabs']['overview']['header'] = '<tab_name>';

Multi Actions

Multi actions are actions which can be applied to multiple entities at once in the listing view.

MultiActions2.png

They rely on JavaScript events. These options can be set the following way:

$options['multiActions'][<action_name>] = array(
    'title' => <action_title>,
    'jsEvent' => <js_event_name>,
);

The title option is optional. If not specified $_ARRAYLANG['<action_name>'] is used (if set).

The following example code can be used to create a custom multi action:

In a Controller class:

$options['multiActions']['delete'] = array(
    'title' => $_ARRAYLANG['TXT_MODULE_TODOMANAGER_MULTIACTIONS_MYACTION'],
    'jsEvent' => 'action:scope',
);

In a corresponding JavaScript file:

cx.jQuery(document).ready(function() {
    cx.bind("action", function (ids) {
        // ids is the list of selected IDs
        // Handle your action here. For example you may call a JsonAdapter from here.
    }, "scope");
});

Field order

Field display order can be specified for overview and form views separately. Simply provide an array with the field names in the desired order to the following options. Not specified fields are appended at the end.

$options['order']['overview'] = <fieldlist>;
$options['order']['form'] = <fieldlist>;

Not implemented yet!

$options['order']['show'] = <fieldlist>;

Field options

These options can be set the following way:

$options['fields'][<field_name>][<option_name>] = <option_value>;
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
showOverview boolean true / false true Whether to show this field in overview views.
showDetail boolean true / false true Whether to show this field in detail views.
readonly boolean true / false false Whether this field should be unchangeable in detail views.
editable boolean true / false false Whether this field should be editable in overview views. Important The function editable must also be activated. See Functions
sorting boolean true / false Value of "sorting" functions option Whether the overview list can be sorted by this field.
validValues string / array List of valid values (CSV or array) or a regular expression (empty) Used for input validation and to specify values for selection field types (see "type" field option). The regular expression is used in PHP and JavaScript, so make sure it is cross-compatible!
tooltip string User interface text (empty) Tooltip to add to this field in edit views.
header string User interface text (empty) User interface name of the field. Falls back to the field's name if not set. Tries to load from $_ARRAYLANG.
formtext string User interface text (empty) User interface name of the field for detail view. Falls back to the "header" field option if not set. Tries to load from $_ARRAYLANG.
type string Field type (empty) Overrides the automatic selection of the field type
mode string Field type mode (see field types) (empty) Field type specific mode
attributes array Key-value pairs of HTML element attributes (empty) Additional HTML attributes of the form element field for detail view.
length int Input max. length (empty) Sets the max. length of an input field. If empty, length is not set[1]. For relations with fetch set to "EXTRA_LAZY" this can be used to set the limit of related entities (default: system paging default).
formfield callback \Cx\Core\Html\Model\Entity\HtmlElement or HTML code (empty) Overrides the automatic form field generation for this field in detail view.

Callback arguments are: $fieldname, $fieldtype, $fieldlength, $fieldvalue, $fieldoptions, $entityId

table array See Custom rendering of list view (empty) Use to customize the rendered HTML of the field in list view.
show array See Custom rendering of show view (empty) Use to customize the rendered HTML of the field in show view.
valueCallback callback field values (empty) Overrides the value for this field in overview and detail view.
Callback arguments are: $fieldvalue, $fieldname, $rowData (only in overview), $fieldoption, $vgId
storecallback callback array, key-value pairs of field names and values (empty) Allows altering POST data before persisting. Used together with "formfield" field option. Return value is persisted.
Callback arguments are: $value, $fieldName, $entity, $entityData
postCallback callback entity (empty) Allows the entity to be edited again after persistence and flushing. Use this if you need the entity ID to save a field. Return entity is persisted and flushed. Callback arguments are: $postedValue, $fieldName, $entity
allowSearching boolean true / false false Whether to include this file in search by term (/"simple search").
allowFiltering boolean true / false true Whether to show this field in filter (/"advanced search").
filterHeader string User interface text (empty) Used as field title in filter (/"advanced search"). Falls back to use "header" field option.
filterOptionsField callback / string \Cx\Core\Html\Model\Entity\HtmlElement or HTML code (empty) Overrides the automatic field generation for filter (/"advanced search") for this field in detail view.
Callback arguments are: $parseObject, $fieldName, $elementName
  1. This is currently broken

Custom rendering of list view

The option table allows for customization of how a field (identified by <field_name>) gets rendered in the list view.

Use as follows:

$options['fields'][<field_name>]['table'][<option_name>] = <option_value>;
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
attributes array array('<html-attribute>' => '<html-attribute-value>') (empty) Use to set additional HTML attributes on the rendered cell (HTML-td-element) of the field <field_name>.
parse callback \Cx\Core\Html\Model\Entity\HtmlElement or HTML code (empty) Use to overrides the automatic field rendering.

Callback arguments are: $value, $rowData, $fieldOptions, $viewGeneratorId


Custom rendering of show view

Upcoming feature. Not yet available.

The option show allows for customization of how a field (identified by <field_name>) gets rendered in the show view.

Use as follows:

$options['fields'][<field_name>]['show'][<option_name>] = <option_value>;
Option name (<option_name>) Option value (<option_value>) Description
Datatype Possible values Default
show boolean true / false (empty) Whether to show this field in show (readonly) views.
encode boolean true / false false Whether the output should be encoded in show (readonly) views.
header string User interface text (empty) User interface name of the field. Falls back to the field's name if not set. Tries to load from $_ARRAYLANG.
parse callback \Cx\Core\Html\Model\Entity\HtmlElement or HTML code (empty) Overrides the automatic field generation for this field in show (readonly) view. Callback arguments are: $value, $entity, $options


Custom fields

These custom fields only work for Doctrine views.
Field options can also be used for custom fields.

To store a custom field you have to implement a storeCallback. See storeCallback
These callbacks are called after the respective callbacks of normal fields.

$options['fields']['customField'] => array(
    'custom' => true,
);

The custom option has no effect on existing fields.

Field types

Type name PHP values Rendered as Available modes (mode) Remarks
bool, boolean True or false Yes/no checkboxes
int, integer True or false input element of type "number" with validator
Cx\Core\Base\EntityBase Any entity select or ajax window create [1], associate Used for relations of the current entity
Country ID of a \Cx\Core\Country\Controller\Country object select field with countries
date, datetime, DateTime Instance of \DateTime or date in ASCMS_DATE_FORMAT input with activated datepicker
multiselect, select Selected value(s) as (comma separated) string select field "validValues" field option is used to generate the list
slider integer jQuery slider "validValues" field option is used for min. and max. values (format: "<min>(,<max>)")
checkboxes, radio Selected value(s) as (comma separated) string list of checkboxes or radiobuttons modern "validValues" field option is used to generate the list Mode "modern" is not implemented yet! Mode "modern" passes the form-data as an array
text string textarea
phone string input element of type "phone"
mail string input element of type "mail" with validator
uploader string MediaBrowser "Browse" button Sets the file path as value of the field
image string MediaBrowser "Browse" button Sets the file path as value of the field, overwrites MediaBrowser settings with field options.
sourcecode string Code editor js, yml, yaml This is currently broken. Renders a Code editor. If mode is set, the editor mode is set accordingly.
wysiwyg string WYSIWYG editor small, full, bbcode This is not implemented yet! Renders a WYSIWYG editor. If mode is set, WYSIWYG mode is set accordingly.
hidden string input field of type "hidden"
string string input field of type "text" normal [1], nocomplete Renders a text field. Mode "nocomplete" suppressed autocompletion for usernames by browsers.
password string input field of type "password" normal [1], nocomplete Renders a password field. Mode "nocomplete" suppressed autocompletion by browsers.
  1. 1.0 1.1 1.2 This is the default value

Call an exposed method

In order to call an exposed method you need to define an array in the following form:

array(
    'adapter' => <adapterName>,
    'method' => <methodName>,
)

The arguments passed to these methods can be seen in the documentation of the respective option. The specified method will receive the parameters in $params['get'].

Please note that there are some cases where the array keys differ. If this is the case this is stated in the documentation of the respective option.

Custom Exception/ Error Message

To show a custom error message throw a new ShinyException in your callback function (e.g. storecallback)

throw new \Cx\Core\Error\Model\Entity\ShinyException('Custom message');

Methods

ViewGenerator provides the following methods to generate URLs to it:

  • getEditUrl($entryOrId, $url = null)
  • getShowUrl($entryOrId, $url = null)
  • getDeleteUrl($entryOrId)
  • getCreateUrl($url = null)
  • getSearchUrl($term, $url = null)
  • getExtendedSearchUrl($criteria, $url = null)
  • getSortUrl($sort, $url = null)
  • getPagingUrl($pos, $url = null)
  • getAddUrl($url = null)

Alternatively, there's a static method for each of those starting with "getVg...". The first parameter is $vgId (which normally is 0). Example:

  • getVgEditUrl($vgId, $entryOrId, $url = null)

URL Format

In order to allow multiple instances of auto-generated views at the same time that do not interfere with each other even when searching, filtering, sorting or paging there's a special format for URL parameters for such parameters:

<attribute>={<vgId>,(<attrId>=)<attrValue>}(,...)

Valid examples:

  • term={0,foo}
  • search={0,foo=bar},{1,alice=bob}