Les DCA

Les DCA

Généralitées

Un DCA est une partie du tableau de $GLOBALS (=>$GLOBALS['tl_dca'] ) .

Les DCA servent à présenter un type de donnée, comment elle sera enregistrée, maniée, affichée. Les DCA se moquent si on est dans le backend ou le frontend.

Définir l'appel aux DCA pour le backend

On liste pages de DCA qu'on utilise dans la configurations globale (config.php ==> backend !):

$GLOBALS['BE_MOD'][{name_part}][{name_module}]['tables'][{num_DCA}] = "{nom_fichier_dca_sans_php}"

  • name_part: Partie du backend dans laquelle est rangée le module
  • name_module: Nom du module backend
  • num_DCA: Entier correspondant au numero de votre DCA (un module peut utiliser plusieurs DCA)

En chargeant un module, le système va donc charger ses DCA associés.

Un DCA est découpé en quatre parties:

  • Ses options générales ['tl_dca']['config'] (qui ne sont pas déclarées si le DCA est déjà défini et qu'on ne fait qu'y rajouter des éléments)

    • (avec au moins $GLOBALS['TL_DCA'][$strTable]['config']['dataContainer'] = {string}

  • Ses palettes, regroupement de champs (type de donnée), la palette default est obligatoire ! Cette partie liste juste les fields (champs) présents dans le DCA ['tl_dca']['palettes']

    • Voir aussi les sous palettes

  • Ses Champs (fields) ['tl_dca']['fields']

  • La manière dont sont listés les entrées (list). ['tl_dca']['list']

    • Lorsqu'il n'y a qu'une seule entrée (comme pour des options), utilisez $GLOBALS['TL_DCA']['tl_{name}']['config']['closed'] = true, et ne remplissez rien dans list.

DCA prédéfinis

Pour ajouter un élément (de formulaire) à un DCA prédéfini, il faut jouer sur le fait que chaque DCA est divisé en palettes. Il faut donc rajouter une nouvelle palette, ou ajouter des champs à la palette par défaut.

tl_settings

tl_settings est un dca particulier puisqu'il correspond aux options générales du système ! (dans le backend c'est ce que vous trouvez dans système/configuration)

    $GLOBALS['TL_DCA']['tl_settings']['palettes']['default']

.= ';{_legend:hide},field1,field2';

    $GLOBALS['TL_DCA']['tl_settings']['fields']

Vous pouvez vous faire une idée de ce qui a déjà été chargé dans mon décryptage du chargement de globals par les fichiers.

tl_content

    (/system/modules/*/dca/tl_content.php).

tl_module

    (/system/modules/*/dca/tl_module.php).

tl_module est un DCA utilisé pour enregister les paramètres de chaque module affichés dans le frontend (notamment le comportement). Il est lié à la table SQL tl_module, l'ajout de champs ici doit dont être répercuté dans le fichier database.sql (voir l'article sur la création d'un module dans le frontend)

tl_user

    (/system/modules/*/dca/tl_user.php).

Paramètres des DCA

La majorité de cette partie est une copie de la documentation officielle de contao.fr : http://wiki.contao.fr/developpeur/guide/dca/reference

Table configuration

    ($GLOBALS['TL_DCA']['tl_{name}']['config'])

Key

Value

Description

label

&$GLOBALS['TL_LANG']
string

The label is used with page or file trees and typically includes reference to the language array.

ptable

Parent table
string

Name of the related parent table (table.pid = ptable.id).

ctable

Child tables
array

Name of the related child tables (table.id = ctable.pid).

dataContainer

Data Container
string

'Table' (database table), 'File' (local configuration file) or 'Folder' (file manager).

validFileTypes

File types
string

Comma separated list of valid file extensions (applies to file trees only).

uploadScript

File name
string

Name of the FancyUpload script in the system/config folder (without file extension).

closed

true/false
boolean

If true, you cannot add further records to the table.

Utilisé à priori pour les données à une seule entrée.

notEditable

true/false
boolean

If true, the table cannot be edited.

switchToEdit

true/false
boolean

Activates the "save and edit" button when a new record is added (sorting mode 4 only).

enableVersioning

true/false
boolean

If true, Contao saves the old version of a record when a new version is created.

doNotCopyRecords

true/false
boolean

If true, Contao will not duplicate records of the current table when a record of its parent table is duplicated.

doNotDeleteRecords

true/false
boolean

If true, Contao will not delete records of the current table when a record of its parent table is deleted.

onload_callback

Callback function
array

Calls a custom function when a DataContainer is initialized and passes the DataContainer object as argument.

onsubmit_callback

Callback function
array

Calls a custom function after a record has been updated and passes the DataContainer object as argument.

ondelete_callback

Callback function
array

Calls a custom function when a record is deleted and passes the DataContainer object as argument.

oncut_callback

Callback function
array

Calls a custom function when a record is moved and passes the DataContainer object as argument. Added in version 2.8.2.

oncopy_callback

Callback function
array

Calls a custom function when a record is duplicated and passes the insert ID and the DataContainer object as argument. Added in version 2.8.

Listing records

Sorting

    ($GLOBALS['TL_DCA']['tl_{name}']['list']['sorting'])

 

Key

Value

Description

mode

Sorting mode
integer

0 Records are not sorted
1 Records are sorted by a fixed field
2 Records are sorted by a switchable field
3 Records are sorted by the parent table
4 Displays the child records of a parent record (see style sheets module)
5 Records are displayed as tree (see site structure)
6 Displays the child records within a tree structure (see articles module)

flag

Sorting flag
integer

1 Sort by initial letter ascending
2 Sort by initial letter descending
3 Sort by initial two letters ascending
4 Sort by initial two letters descending
5 Sort by day ascending
6 Sort by day descending
7 Sort by month ascending
8 Sort by month descending
9 Sort by year ascending
10 Sort by year descending
11 Sort ascending
12 Sort descending

panelLayout

Panel layout
string

search show the search records menu
sort show the sort records menu
filter show the filter records menu
limit show the limit records menu

Separate options with comma (= space) and semicolon (= new line) like sort,filter;search,limit.

fields

Default sorting values
array

One or more fields that are used to sort the table.

headerFields

Header fields
array

One or more fields that will be shown in the header element (sorting mode 4 only).

icon

Tree icon
string

Path to an icon that will be shown on top of the tree (sorting mode 5 and 6 only).

root

Root nodes
array

IDs of the root records (pagemounts). This value usually takes care of itself.

Works with DC_Folder !

filter

Query filter
array

Allows you to add custom filters as arrays, e.g. array('status=?', 'active'). Added in version 2.9.0.

disableGrouping

true/false
boolean

Allows you to disable the group headers in list view and parent view.

paste_button_callback

Callback function
array

This function will be called instead of displaying the default paste buttons. Please specify as array('Class', 'Method').

child_record_callback

Callback function
array

This function will be called to render the child elements (sorting mode 4 only). Please specify as array('Class', 'Method').

child_record_class

CSS class
string

Allows you to add a CSS class to the parent view elements.

Labels

    ($GLOBALS['TL_DCA']['tl_{name}']['list']['label'])

Key

Value

Description

fields

Fields
array

One or more fields that will be shown in the list.

format

Format string
string

HTML string used to format the fields that will be shown (e.g. <strong>%s</strong>).

maxCharacters

Number of characters
integer

Maximum number of characters of the label.

group_callback

Callback function
array

Call a custom function instead of using the default group header function.

label_callback

Callback function
array

Call a custom function instead of using the default label function.

 

Operation

Global operations

    ($GLOBALS['TL_DCA']['tl_{name}']['list']['global_operations']['all'])

Key

Value

Description

label

&$GLOBALS['TL_LANG']
string

Button label. Typically a reference to the global language array.

href

URL fragment
string

URL fragment that is added to the URI string when the button is clicked (e.g. act=editAll).

class

CSS class
string

CSS class attribute of the button.

attributes

Additional attributes
string

Additional attributes like event handler or style definitions.

button_callback

Callback function
array

Call a custom function instead of using the default button function. Please specify as array('Class', 'Method').

Regular operations

    ($GLOBALS['TL_DCA']['tl_{name}']['list']['operations']['{name_operation}'])

Key

Value

Description

label

&$GLOBALS['TL_LANG']
string

Button label. Typically a reference to the global language array.

href

URL fragment
string

URL fragment that is added to the URI string when the button is clicked (e.g. act=edit).

icon

Icon
string

Path and filename of the icon.

attributes

Additional attributes
string

Additional attributes like event handler or style definitions.

button_callback

Callback function
array

Call a custom function instead of using the default button function. Please specify as array('Class', 'Method').

 

Fields

    ($GLOBALS['TL_DCA']['tl_{name}']['fields']['{name_field}'])

Key

Value

Description

label

&$GLOBALS['TL_LANG']
string

Field label. Typically a reference to the global language array.

default

Default value
mixed

Default value that is set when a new record is created.

exclude

true/false
boolean

If true the field will be excluded for non-admins. It can be enabled in the user group module (allowed excluded fields).

search

true/false
boolean

If true the field will be included in the search menu (see "sorting records" -> "panelLayout").

sorting

true/false
boolean

If true the field will be included in the sorting menu (see "sorting records" -> "panelLayout").

filter

true/false
boolean

If true the field will be included in the filter menu (see "sorting records" -> "panelLayout").

flag

Sorting mode
integer

1 Sort by initial letter ascending
2 Sort by initial letter descending
3 Sort by initial X letters ascending (see length)
4 Sort by initial X letters descending (see length)
5 Sort by day ascending
6 Sort by day descending
7 Sort by month ascending
8 Sort by month descending
9 Sort by year ascending
10 Sort by year descending
11 Sort ascending
12 Sort descending

length

Sorting length
integer

Allows to specify the number of characters that are used to build sorting groups (flag 3 and 4). Included since version 2.5.3

inputType

Field type
string

text Text field
password Password field
textarea Textarea
select Drop-down menu
checkbox Checkbox
radio Radio button
radioTable Table with images and radio buttons
inputUnit Text field with small unit drop-down menu
trbl Four text fields with a small unit drop-down menu
chmod CHMOD table
pageTree Page tree
fileTree File tree
tableWizard Table wizard
listWizard List wizard
optionWizard Option wizard
moduleWizard Module wizard
checkboxWizard Checkbox Wizard

options

Options
array[int] = string

Options of a drop-down menu or radio button menu, or select (=values => see reference for labels).

options_callback

Callback function
array

Callback function that returns an array of options. Please specify as array('Class', 'Method').

  • Set the return array as ($id=>$designation).
  • Define class in the DCA file (or set an include).
  • Don't use the reference key, you get the designation in the array.

foreignKey

table.field
string

Get options from a database table. Returns ID as key and the field you specify as value.

Use options_callback to have a dynamic designation. Otherwise you have to define the reference key for each value of the BDD...

reference

&$GLOBALS['TL_LANG']
Array[int] =string

Array that holds the options labels. Typically a reference to the global language array.

explanation

&$GLOBALS['TL_LANG']
string

Array that holds the explanation. Typically a reference to the global language array.

input_field_callback

Callback function
array

Executes a custom function instead of using the default input field routine and passes the the DataContainer object and the label as arguments.

eval

Field configuration
array

Various configuration options. See next paragraph.

wizard

Callback function
array

Call a custom function and add its return value to the input field. Please specify as array('Class', 'Method').

load_callback

Callback functions
array

These functions will be called when the field is loaded. Please specify each callback function as array('Class', 'Method'). Passes the field's value and the data container as arguments. Expects the field value as return value.

save_callback

Callback functions
array

These functions will be called when the field is saved. Please specify each callback function as array('Class', 'Method'). Passes the field's value and the data container as arguments. Expects the field value as return value. Throw an exception to display an error message.

Evaluation

    ($GLOBALS['TL_DCA']['tl_{name}']['fields']['{name_field}']['eval'])

Key

Value

Description

helpwizard

true/false
boolean

If true the helpwizard icon will appear next to the field label.

mandatory

true/false
boolean

If true the field cannot be empty.

maxlength

Maximum length
integer

Maximum number of characters that is allowed in the current field.

minlength

Minimum length
integer

Minimum number of characters that have to be entered.

fallback

true/false
boolean

If true the field can only be assigned once per table.

rgxp

Regular expression
string

digit allows numeric characters only
alpha allows alphabetic characters only
alnum allows alphanumeric characters only
prcnt allows numbers between 0 and 100
extnd disallows #&()/<=>
date expects a valid date
time expects a valid time
datim expects a valid date and time
email expects a valid e-mail address
friendly expects a valid "friendly name format" e-mail address
url expects a valid URL
phone expects a valid phone number

cols

Columns
integer

Number of columns (textarea fields only).

rows

Rows
integer

Number of rows (textarea fields only).

wrap

Word wrapping
string

off disable word wrapping
soft soft word wrapping
hard hard word wrapping

multiple

true/false
boolean

Make the input field multiple. Applies to text fields, select menus, radio buttons and checkboxes. Required for the checkbox wizard.

size

Size
integer

Size of a multiple select menu or number of input fields.

style

Style attributes
string

Style attributes (e.g. border:2px)

rte

Rich text editor file
string

tinyMCE use file config/tinyMCE.php
tinyFlash use file config/tinyFlash.php

You can add your own configuration files as well.

submitOnChange

true/false
boolean

If true the form will be submitted when the field value changes.

nospace

true/false
boolean

If true whitespace characters will not be allowed.

allowHtml

true/false
boolean

If true the current field will accept HTML input.

preserveTags

true/false
boolean

If true no HTML tags will be removed at all.

decodeEntities

true/false
boolean

If true HTML entities will be decoded. Note that HTML entities are always decoded if allowHtml is true.

doNotSaveEmpty

true/false
boolean

If true the field will not be saved if it is empty.

alwaysSave

true/false
boolean

If true the field will always be saved, even if its value has not changed (available from version 2.7.RC1). This can be useful in conjunction with a load_callback.

spaceToUnderscore

true/false
boolean

If true any whitespace character will be replaced by an underscore.

unique

true/false
boolean

If true the field value cannot be saved if it exists already.

encrypt

true/false
boolean

If true the field value will be stored encrypted.

trailingSlash

true/false
boolean

If true a trailing slash will be added to the field value. If false, an existing trailing slash will be removed from the field value.

files

true/false
boolean

If true files and folders will be shown. If false, only folders will be shown. Applies to file trees only.

filesOnly

true/false
boolean

Removes the radio buttons or checkboxes next to folders. Applies to file trees only.

extensions

File extensions
string

Limits the file tree to certain filetypes (comma separated list). Applies to file trees only.

path

Path
string

Custom root directory for file trees. Applies to file trees only.

fieldType

Input field type
string

checkbox allow multiple selections
radio allow a single selection only

Applies to file- and pagetrees only.

includeBlankOption

true/false
boolean

If true a blank option will be added to the options array. Applies to drop-down menus only.

blankOptionLabel

Label
string

Label for the blank option (defaults to -).

findInSet

true/false
boolean

Sort by the actual option values instead of their labels (available from version 2.7.RC1).

datepicker

Date picker
string

Date picker configuration string.

feEditable

true/false
boolean

If true the current field can be edited in the frontend. Applies to table tl_member only.

feGroup

Group name
string

personal personal data
address address details
contact contact details
login login details

Applies to table tl_member only. You can also define your own groups.

feViewable

true/false
boolean

If true the current field is viewable in the member listing module (version 2.6.2).

doNotCopy

true/false
boolean

If true the current field will not be duplicated if the record is duplicated.

hideInput

true/false
boolean

If true the field value will be hidden (it is still visible in the page source though!).

doNotShow

true/false
boolean

If true the current field will not be shown in "edit all" or "show details" mode.

isBoolean

true/false
boolean

Indicates that a particular field is boolean.

disabled

true/false
boolean

Disables the field (not supported by all field types).

readonly

true/false
boolean

Makes the field read only (not supported by all field types).

Palettes

    ($GLOBALS['TL_DCA']['tl_{name}']['palettes']['{name_palette}'])

    Contient la liste des champs

Il doit obligatoirement y avoir une palette 'default', qui représente les différents champs contenus.

Il peut y avoir également une clé '__selector__', qui permet de modifier dynamiquement les champs présents dans des sous palettes ('subpalettes').

Sous Palettes

    ($GLOBALS['TL_DCA']['tl_{name}']['subpalettes'])

Elles sont déclarées dans la palette __selector__ comme array.

Par exemple, pour tl_settings.php:

'palettes' => array

(

'__selector__' => array('useSMTP'),

'default' => '{title_legend},websiteTitle,adminEmail;{date_legend},dateFormat,timeFormat,datimFormat,timeZone;{global_legend:hide},websitePath,characterSet,customSections,enableGZip;{backend_legend},backendTheme,resultsPerPage,doNotCollapse,pNewLine;{frontend_legend},urlSuffix,cacheMode,rewriteURL,disableAlias;{security_legend:hide},allowedTags,lockPeriod,encryptionKey,displayErrors,debugMode,disableRefererCheck,disableIpCheck;{files_legend:hide},uploadTypes,allowedDownload,editableFiles,validImageTypes,maxImageWidth,jpgQuality;{uploads_legend:hide},uploadPath,fancyUpload,uploadFields,maxFileSize,imageWidth,imageHeight;{search_legend:hide},enableSearch,indexProtected;{smtp_legend:hide},useSMTP;{modules_legend},inactiveModules;{timeout_legend:hide},undoPeriod,versionPeriod,logPeriod,sessionTimeout;{chmod_legend:hide},defaultUser,defaultGroup,defaultChmod;{update_legend:hide},liveUpdateBase'

),

'subpalettes' => array

(

'useSMTP' => 'smtpHost,smtpPort,smtpUser,smtpPass'

),

Notes sur les langues et la définition des palettes

Lorsque vous définissez les palettes, vous pouvez créer des sous parties en utilisant "{{label_defini}}" et en précédent d'un point virgule  (sauf pour le premier) à la place d'une virgule normale. Le label que vous mettrez entre les accolades devra ensuite être défini dans le fichier langue correspondant (tl_{nom_dca}.php) ainsi :

$GLOBALS['TL_LANG'][{nom_dca}][{label_défini}] = 'valeur dans le langage';


  Cet article est sous licence LGPL, vous pouvez le modifier, le copier et le publier, mais en signalant son auteur d'origine. ( http://www.ilune.fr )