Autogenerated Views

From Cloudrexx Development Wiki
(Redirected from View Autogeneration)
Jump to: navigation, search

Cloudrexx can generate views for you automatically. To generate views based on Doctrine entities or arrays (/DataSets) the class \Cx\Core\Html\Controller\ViewGenerator is used. It can create list views (called "overview") and form views (called "detail view"). ViewGenerator does not only generate views, it also handles the interaction with them. This way you can perform actions like create, edit, copy, delete, sort, filter and so on in these views. In case the render object is a Doctrine entity ViewGenerator lets you edit relations to other entities.

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().

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, $options);
echo $view;

$renderObject can be one of the following:

  • An absolute entity class name of an entity managed by Doctrine (this includes YamlEntities)
  • An object
  • An array of objects
  • A two dimensional array
  • An instance of \Cx\Core_Modules\Listing\Model\Entity\DataSet

For $options, see the available options below.

Options

ViewGenerator accepts an array with options. The first level of the array contains the entity name(s). This is needed, as one instance of ViewGenerator can show fields of multiple entities.

If the object to be rendered is not an entity (but an instance of DataSet initialized with an array), a second level is added with the DataSet identifier.

The following sections show all possible options that can be set this way. In these examples $options is the content after this identification.

// if the render object is a set of entities:
$vgOptions[<entity_name>] = $options;

// if the render object is an instance of DataSet initialized with an array:
$vgOptions['Cx\Core_Modules\Listing\Model\Entity\DataSet'][<dataset_identifier>] = $options;

Root level options

These options can be set the following way:

$options[<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
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.
cancelUrl \Cx\Core\Routing\Url Request URL URL used as jump-back on cancel
preRenderDetail callback \Cx\Core\Html\Model\Entity\HtmlElement or HTML code (empty) Allows adding a callback before detail view is rendered. The return value is appended at the end of the form.
Callback arguments are: $viewGenerator, $formGenerator, $entityId
rowAttributes callback Associative array of attributes (empty) Allows full control over row attributes. Already set attributes are passed to the callback as second argument.
Callback arguments are $rowData, $attributes
showPrimaryKeys boolean true / false false This is not implemented yet! Show the primary keys in the edit view.
  1. BackendController::getViewGeneratorOptions() sets this to $_ARRAYLANG['TXT_<component_type>_<component_name>_ACT_<class_identifier>'] if this index is set.

Template

Uses a different template to parse. Specify a filename relative to the root directory of Cloudrexx. These options can be set the following way:

 $options['template'][<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
table string filename core/Html/View/Template/Generic/Table.html Uses a different template to parse the table in the overview. Specify a filename relative to the root directory of Cloudrexx.
tableView string filename core/Html/View/Template/Generic/TableView.html Uses a different template to parse the overview. Specify a filename relative to the root directory of Cloudrexx.


Functions

These options can be set the following way:

$options['functions'][<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
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.
sorting boolean true / false false [1] Default value for field option "sorting"
order array Key-value pairs of field names => SORT_ASC / SORT_DESC (empty) If used, lets the user automatically sort entries by the first column. The first entry's key must be the same as the first entry's key of sortBy/field function option. See Sorting.
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
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.
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
  1. 1.0 1.1 1.2 1.3 1.4 1.5 1.6 BackendController::getViewGeneratorOptions() sets this to true

Sorting

These options can be set the following way:

$options['functions']['sortBy'][<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
field array Key-value pairs of field names => SORT_ASC / SORT_DESC (empty) Sorts list by these fields by default.
jsonadapter array Keys "object" and "act" of a JsonAdapter (empty) Overrides the default handler for changes in order in overview if "order" function option is in use.


Status

These option can be set the following way:

$options['functions']['status'][<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
field string Field name (empty) Updates the status of this field.
jsonadapter array Keys "object" and "act" of a JsonAdapter (empty) Overrides the default handler for changes in status in overview if "status" function option is in use.


Export

These options can be set the following way:

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

If $options['functions']['export'] is not set or set to anything other than an array export is disabled. All options are optional.

Option name Possible datatypes Possible values Default value Description
jsonadapter array Keys "object" and "act" of a JsonAdapter (empty) Overrides the default handler to trigger an export.
fieldList array List of fields (empty) This is not implemented yet! Overrides the default list of fields / field order to export. By default all fields are exported in order of appearance.


Overwrite Delete onClick Event

The JavaScript OnClick event on the delete function can be overwritten the following way:

$options['functions']['onclick']['delete'] = <js_callback_function_name>

JavaScript function

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


Tabs

Multiple tabs can be created in the detail view of an entry. Can be used with large entries to simplify the form view. Fields that are not assigned in any tab are automatically displayed in the default tab.
To define a tab title, set $_ARRAYLANG[<tab_name>] or use the header option.

$options['tabs'][<tab_name>]['header'] = <tab_title>;  
$options['tabs'][<tab_name>]['fields'] = <fieldlist>;

To overwrite the title of the overview:

$options['tabs']['overview']['header'] = <tab_name>;

Multi Actions

Multi actions are actions which can be applied to multiple entities at once in the overview. 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).

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 Possible datatypes Possible values Default value Description
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
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) This is not implemented yet! 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

Overview options

These options can be set the following way:

$options['fields'][<field_name>]['table'][<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
attributes array Key-value pairs of HTML element attributes (empty) Additional HTML attributes of the form element field for detail view.
parse callback \Cx\Core\Html\Model\Entity\HtmlElement or HTML code (empty) Overrides the automatic form field generation for this field in overview.
Callback arguments are: $value, $rowData, $fieldOptions, $viewGeneratorId


Show options

This is not implemented yet! These options can be set the following way:

$options['fields'][<field_name>]['show'][<option_name>] = <option_value>;
Option name Possible datatypes Possible values Default value Description
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.

Define a callback

There are two different types of callbacks:

  • PHP callback method
  • JsonAdapter

We strongly recommend to use JsonAdapters as callbacks. PHP callbacks do not work with views with Doctrine relations. Windows showing the relation forms are loaded via AJAX and the information about the callback needs to be passed via AJAX. Since PHP callbacks cannot be serialized, JsonAdapters are a requirement for these views to work properly.

In order to specify a JsonAdapter callback use the following scheme to define your callback:

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

The specified method of the JsonAdapter will receive the parameters in $params['get'].

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');

Field types

Type name PHP values Rendered as Available modes 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 textarea 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 Mode "nocomplete" is not implemented yet! Renders a text field. Mode "nocomplete" suppressed autocompletion for usernames by browsers.
password string input field of type "password" normal [1], nocomplete This is not implemented yet! Renders a password field. Mode "nocomplete" suppressed autocompletion by browsers.
  1. 1.0 1.1 1.2 This is the default value

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($esort, $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}