In-Portal Developers Guide

This is a wiki-based Developers Guide for In-Portal Open Source CMS. The purpose of this guide is to provide advanced users, web developers and programmers with documentation on how to expand, customize and improve the functionality and the code the In-Portal software. Please consider contributing to our documentation writing effort.

K4:Defining Database, Virtual and Calculated Fields

From In-Portal Developers Guide

(Difference between revisions)
Jump to: navigation, search
Current revision (05:17, 28 November 2010) (view source)
(Side-box)
 
(7 intermediate revisions not shown.)
Line 37: Line 37:
|-
|-
| {{ConfigProperty|not_null|int}} || If the field in the database is setup as "<code>NOT NULL</code>", then this option needs to be set.
| {{ConfigProperty|not_null|int}} || If the field in the database is setup as "<code>NOT NULL</code>", then this option needs to be set.
 +
|-
 +
| {{ConfigProperty|totals|string}} || Название агрегатной функции базы данных (напр. <code>AVG</code>, <code>SUM</code>, <code>COUNT</code> и т.п.), которая будет использоваться для подсчёта <code>total</code> значения по колонке, в которой будет выводиться это поле.
|}
|}
Line 61: Line 63:
| {{ConfigProperty|current_table_only|boolean}} || Checks whether a value in a field is [[#unique|unique]] in the current table (live or temporary). By default, the field is checked in both the live and temporary tables (if accessible).
| {{ConfigProperty|current_table_only|boolean}} || Checks whether a value in a field is [[#unique|unique]] in the current table (live or temporary). By default, the field is checked in both the live and temporary tables (if accessible).
|-
|-
-
| {{ConfigProperty|required|int, boolean}} || Поле обязательно к заполнению. Если значение не указано, то в поле будет ошибка. Несмотря на ошибочное мнение '''ноль''', в качестве значения поля не вызывает ошибку о том, что в поле не указано значение. Но если 0, указанный в качестве значения, должен вызывать ошибку можно дополнительно указать опции ограничения интервала значения, напр. '''<code>'min_value_exc' => 0</code>'''.  
+
| {{ConfigProperty|required|int, boolean}} || '''<code>'min_value_exc' => 0</code>'''. Field must be filled in. If a value is not set, then the field will contain an error. '''Zero''' as the field value doesn't result in an error saying that the field wasn't filled in. However, if the field value being set to zero should result in an error, it's possible to additionally set an interval for what the value must be, for example '''<code>'min_value_exc' => 0</code>'''.
 +
 
|}
|}
-
Все выше описанные опции можно объединить в группы по смыслу:  
+
All of the above described options can be combined into meaningful groups:
-
* '''интервалы''' (''<code>max_value_inc</code>'', ''<code>min_value_inc</code>'', ''<code>max_value_exc</code>'', ''<code>min_value_exc</code>'') - опции, использующиеся для проверки принадлежности значения поля указанному интервалу (range);
+
* '''intervals''' (''<code>max_value_inc</code>'', ''<code>min_value_inc</code>'', ''<code>max_value_exc</code>'', ''<code>min_value_exc</code>'') - options used for checking whether a field value falls in the indicated range.
-
* '''длинна''' (''<code>max_len</code>'', ''<code>min_len</code>'') - опции, использующиеся для проверки длинны строки (length).
+
* '''length''' (''<code>max_len</code>'', ''<code>min_len</code>'') - options used for checking the length of a String.
-
{{TipBox|Если та, или иная опция не нужна, то можно просто убрать её определение из массива опций поля. В таком случае не надо будет ставить её значение в ''<code>0</code>'' или ''<code>false</code>''.}}
+
{{TipBox|If one or another option is not need, then its declaration can simply be removed from the array of field options, making it not necessary to set its value to ''<code>0</code>'' or ''<code>false</code>''.}}
-
== Сообщения об ошибках ==
+
== Error Messages ==
-
У каждого поля можно указать альтернативные тексты для всех ошибок используя опцию {{ConfigProperty|error_msgs|array}}. Ниже приведена таблица, в которой описаны все стандартные ошибки:
+
For each field it's possible to set alternative error message text for all error messages by using the option {{ConfigProperty|error_msgs|array}}. The below table describes all standard errors:
{| class="prettytable"
{| class="prettytable"
-
! pseudo || описание || значение по умолчанию || управляется опциями
+
! Pseudo || Description || Default Value || Controlled by Options
|-
|-
-
| <code>required</code> || Значение в поле не заполнено. || <code>!la_err_required!</code> || [[#required|required]]
+
| <code>required</code> || Field value not filled in. || <code>!la_err_required!</code> || [[#required|required]]
|-
|-
-
| <code>unique</code> || Значение в поле не уникально. || <code>!la_err_unique!</code> || [[#unique|unique]]
+
| <code>unique</code> || Field value not unique. || <code>!la_err_unique!</code> || [[#unique|unique]]
|-
|-
-
| <code>value_out_of_range</code> || Значение в поле не находиться в разрешённом интервале значений || <code>!la_err_value_out_of_range!</code> || [[#max_value_inc|max_value_inc]], [[#min_value_inc|min_value_inc]], [[#max_value_exc|max_value_exc]], [[#min_value_exc|min_value_exc]]
+
| <code>value_out_of_range</code> || Field value is not within the indicated range || <code>!la_err_value_out_of_range!</code> || [[#max_value_inc|max_value_inc]], [[#min_value_inc|min_value_inc]], [[#max_value_exc|max_value_exc]], [[#min_value_exc|min_value_exc]]
|-
|-
-
| <code>length_out_of_range</code> || Длинна строки превышена. || <code>!la_err_length_out_of_range!</code> || [[#max_len|max_len]], [[#min_len|min_len]]
+
| <code>length_out_of_range</code> || String too long. || <code>!la_err_length_out_of_range!</code> || [[#max_len|max_len]], [[#min_len|min_len]]
|-
|-
-
| <code>bad_type</code> || Тип значения в поле не соответствует описанию поля (напр. ввели букву вместо числа). || <code>!la_err_bad_type!</code> || [[#type|type]]
+
| <code>bad_type</code> || Field value type isn't the type it's set to be (for example, a character was entered instead of an integer). || <code>!la_err_bad_type!</code> || [[#type|type]]
|-
|-
-
| <code>invalid_format</code> || Формат строки не соответствует требуемому. || <code>!la_err_invalid_format!</code> || [[#regexp|regexp]]
+
| <code>invalid_format</code> || String format isn't as required. || <code>!la_err_invalid_format!</code> || [[#regexp|regexp]]
|-
|-
-
| <code>bad_date_format</code> || Формат введённой даты не соответствует требуемому. || <code>!la_err_bad_date_format!</code> || [[K4:Formatters#kDateFormatter|опции kDateFormatter]]
+
| <code>bad_date_format</code> || Date format isn't as required. || <code>!la_err_bad_date_format!</code> || [[K4:Formatters#kDateFormatter|опции kDateFormatter]]
|-
|-
-
| <code>primary_lang_required</code> || Значение в поле на первичном (primary) языке не заполнено. || <code>!la_err_primary_lang_required!</code> || [[#required|required]], [[K4:Formatters#kMultiLanguage|опции kMultiLanguage]]
+
| <code>primary_lang_required</code> || Field value not entered in primary language. || <code>!la_err_primary_lang_required!</code> || [[#required|required]], [[K4:Formatters#kMultiLanguage|kMultiLanguage Options]]
|-
|-
-
| <code>bad_file_format</code> || Попытка загрузить файл, у которого миме-тип (<code>mime-type</code>) не находиться в списке разрешённых. || <code>!la_error_InvalidFileFormat!</code> || [[K4:Formatters#allowed_types|allowed_types]], [[K4:Formatters#kUploadFormatter|опции kUploadFormatter]]
+
| <code>bad_file_format</code> || Attempt to upload a file whose (<code>mime-type</code>) isn't in the allowed types. || <code>!la_error_InvalidFileFormat!</code> || [[K4:Formatters#allowed_types|allowed_types]], [[K4:Formatters#kUploadFormatter|опции kUploadFormatter]]
|-
|-
-
| <code>bad_file_size</code> || Попытка загрузить файла, размер которого превышает разрешённый. || <code>!la_error_FileTooLarge!</code> || [[K4:Formatters#max_size|max_size]], [[K4:Formatters#kUploadFormatter|опции kUploadFormatter]]
+
| <code>bad_file_size</code> || Attempt to upload a file whose size is greater than allowed maximum size. || <code>!la_error_FileTooLarge!</code> || [[K4:Formatters#max_size|max_size]], [[K4:Formatters#kUploadFormatter|опции kUploadFormatter]]
|-
|-
-
| <code>cant_save_file</code> || Загруженный на сервер файл неудалось сохранить в требуемую директорию. || <code>!la_error_cant_save_file!</code> || [[K4:Formatters#upload_dir|upload_dir]], [[K4:Formatters#kUploadFormatter|опции kUploadFormatter]]
+
| <code>cant_save_file</code> || File uploaded to the server couldn't be saved to the requested directory. || <code>!la_error_cant_save_file!</code> || [[K4:Formatters#upload_dir|upload_dir]], [[K4:Formatters#kUploadFormatter|опции kUploadFormatter]]
|}
|}
-
Эта опция задаётся в виде ассоциативного одномерного массива, в ключах которого указаны "<code>pseudo</code>" ошибок (см. приведённую выше таблицу), а в значениях соответствующие им тексты ошибок:
+
This option is set in the form of an associative one-dimensional array, where each key is an error's "<code>pseudo</code>" (see the above table) and each field is the error message.
<source lang="php">
<source lang="php">
Line 104: Line 107:
)
)
</source>
</source>
-
Если требуется чтобы перевод фразы стал текстом сообщения об ошибке, то нужно заключить её название в восклицательные знаки:
+
To make it so that a phrase translation is used as an error message it's name must be enclosed in exclamation marks:
-
* "<code>!la_error_ErrorPhrase!</code>" - фраза (её перевод на текущем языке это текст ошибка);
+
* "<code>!la_error_ErrorPhrase!</code>" - phrase (it's translation in the current language will be the error message);
-
* "<code>Error Message</code>" - текст (будет один для всех языков).
+
* "<code>Error Message</code>" - text (will be the same for all languages).
-
 
+
-
== Опции форматера ==
+
-
Все оставшиеся опции обрабатываются указанным [[K4:Formatters|форматером]]. Вот, к примеру некоторые из них:
+
 +
== Formatter Options ==
 +
All of the remaining options are processed with specific [[K4:Formatters|formatters]]. Some of them for example are:
{| class="prettytable"
{| class="prettytable"
-
! название опции || описание опции
+
! Option Name || Option Description
|-
|-
-
| {{ConfigProperty|formatter|string}} || Название класса накладываемого форматера. Вот самые ходовые классы:  
+
| {{ConfigProperty|formatter|string}} || Name of the formatter's classHere are the most common classes:
-
* [[K4:Formatters#kFormatter|kFormatter]] - для обработки чисел, денежных сумм, почтовых адресов
+
* [[K4:Formatters#kFormatter|kFormatter]] - For processing numbers, monetary amounts, postal addresses
-
* [[K4:Formatters#kOptionsFormatter|kOptionsFormatter]] - для работы с элементами ограниченного выбора (dropdown, radio buttons и т.п.)
+
* [[K4:Formatters#kOptionsFormatter|kOptionsFormatter]] - For working with restricted choice elements (dropdown, radio buttons, etc.)
-
* [[K4:Formatters#kDateFormatter|kDateFormatter]] - для обработки дат
+
* [[K4:Formatters#kDateFormatter|kDateFormatter]] - For processing dates
-
* [[K4:Formatters#kUploadFormatter|kUploadFormatter]] - для загрузки файлов на сервер
+
* [[K4:Formatters#kUploadFormatter|kUploadFormatter]] - For uploading files to the server
-
Подробнее о том, какие есть форматеры и как их использовать можно прочесть в [[K4:Formatters|этой статье]].
+
The specifics about which formatters exist and how to use them can be read in [[K4:Formatters|this article]].
|}
|}
-
== Автоматическое построение структуры ==
+
== Automatic Structuring ==
-
В K4 есть механизм, который автоматически выстраивает массив для опции [[K4:Unit Configs#Fields|Fields]]. Чтобы воспользоваться им следуйте приведённым шагам:
+
K4 has a mechanism that automatically builds an array for [[K4:Unit Configs#Fields|Fields]] options. To use it, following these steps:
-
* пойти в секцию "Configuration -> System Tools" (в Platform) или "Tools -> System Tools" (в In-Portal);
+
* Go to section "Configuration -> System Tools" (in Platform) or "Tools -> System Tools" (in In-Portal);
-
* в поле "Table Structure" вписать '''имя таблицы''' (можно без [[K4:Константы#TABLE_PREFIX|TABLE_PREFIX]]) или [[K4:Unit Configs#Prefix|префикс]] от [[K4:Unit Configs|unit config]];
+
* In the field "Table Structure" enter the '''table name'''' (without [[K4:Константы#TABLE_PREFIX|TABLE_PREFIX]] is ok) or [[K4:Unit Configs|unit config]] [[K4:Unit Configs#Prefix|prefix]];
-
* нажать на кнопку "Go";
+
* Press "Go" button;
-
* откроется новое окно со структурой введённой таблицы:
+
* A new window will open with the structure of the table:
-
[[Image:Table Structure.gif|left|frame|Автоматически построенная структура таблицы]]
+
[[Image:Table Structure.gif|left|frame|Automatically built table structure]]
<br clear="both">
<br clear="both">
-
{{InfoBox|При добавлении новых полей в таблицу нужно повторить все выше описанные шаги, но из результата скопировать описание только нужных полей, а не всех как обычно. Не надо писать всё руками.}}
+
{{InfoBox|When adding new fields to a table all of the above steps need to be taken, but from the result copy only the needed fields rather than all of them as usual. It's not necessary to write everything by hand.}}
 +
 
 +
While building the structure of the fields, the following options are automatically set (if possible to determine):
 +
* '''<code>type</code>''' - PHP data value type that's going to be stored in the field;
 +
* '''<code>not_null</code>''' - NULL or NOT NULL;
 +
* '''<code>default</code>''' - Default value;
 +
* '''<code>formatter</code>''' - Formatter class, for now only for numerical fields (float, double, decimal);
 +
* '''<code>max_len</code>''' - Limit on the length of a field value, only for String fields (varchar).
 +
 
 +
Functionality available starting with [[K4:Core v 4.1.0|Core v 4.1.0]].
-
При построении структуры полям автоматически прописываются (если удаётся определить) следующие опции:
+
[[en:{{FULLPAGENAME}}]]
-
* '''<code>type</code>''' - php тип значения, которое будет храниться в поле;
+
[[ru:K4:Описание_полей_таблицы]]
-
* '''<code>not_null</code>''' - NULL или NOT NULL пометка;
+
-
* '''<code>default</code>''' - значение по умолчанию;
+
-
* '''<code>formatter</code>''' - класс форматера, пока только для дробный полей (float, double, decimal);
+
-
* '''<code>max_len</code>''' - ограничение по длине значения в поле, только для строковых полей (varchar).
+
-
Функциональность доступна начиная с [[K4:Core v 4.1.0|Core v 4.1.0]].
+
Translated from: [http://guide.in-portal.org/rus/index.php?title=K4:%D0%9E%D0%BF%D0%B8%D1%81%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BF%D0%BE%D0%BB%D0%B5%D0%B9_%D1%82%D0%B0%D0%B1%D0%BB%D0%B8%D1%86%D1%8B&oldid=1072 revision 1072]

Current revision

Unit Configs Unit Configs
Статьи в этой категории

Usually, each unit config is created to interact with one database table. For this, each field from the database table must be declared in the unit config. The Fields option exists for this purpose. This option is an associative array (almost all options in a unit config are associative arrays), in which the keys are the names of the table fields and the values are the options of these fields. This array can, for example, look like this:

'Fields' => Array (
	'ProductId' => Array('type' => 'int', 'not_null' => 1, 'default' => 0),
	'Name' => Array ('type' => 'string', 'formatter' => 'kMultiLanguage', 'required' => 1, 'max_len' => 255, 'default' => ''),
	'Description' => Array ('type' => 'string', 'formatter' => 'kMultiLanguage', 'default' => NULL),
),

From the above example it's not difficult to see that ProductId, Name and Description are fields, and the contents of the arrays are the sets of options for these fields. Fields options are divided into 3 groups:

  • required - must always be there;
  • validation - used to validate field values against the restrictions on the field values;
  • formatter - used by the indicated formatter.

Contents

Required Options

Option Name Option Description
type (string) Indicates the type of value that's going to be stored in the field. For all numerical types, it's automatically checked that the field value is a number. If this field has something else, for example a String, then at the validation stage this field will contain an error. The following values are available for this option:
  • int - whole number (e.g. 543);
  • float - floating point number (e.g. 14.66);
  • string - line of text (e.g. 'validate').


Deprecated Types (Don't Use):

  • integer - synonym int;
  • double - synonym float;
  • real - synonym float;
  • numeric - synonym float.
default (mixed) Default field value. Must correspond to the default value of this field in the database. If it's physically impossible (database restriction) to synchronize default values in options and in the database field, then this doesn't have to be done. For example, when using kDateFormatter it's allowed to put '#NOW#' as the default value, but the database field with the date is numeric (since it's a timestamp) and such a value can't be stored in the database.

Not Required Options

Option Name Option Description
not_null (int) If the field in the database is setup as "NOT NULL", then this option needs to be set.
totals (string) Название агрегатной функции базы данных (напр. AVG, SUM, COUNT и т.п.), которая будет использоваться для подсчёта total значения по колонке, в которой будет выводиться это поле.

Validation Options

Option Name Option Description
error_field (string) Name of the field which stores validation error messages in place of this field. It's useful when errors from several virtual fields need to show in one real field.
max_value_inc (int, float) Maximum value (inclusive) that can be in this field. Only for numeric fields.
min_value_inc (int, float) Minimum value (inclusive) that can be in this field. Only for numeric fields.
max_value_exc (int, float) Minimum value (exclusive) that can be in this field. Only for numeric fields.
min_value_exc (int, float) Minimum value (exclusive) that can be in this field. Only for numeric fields.
max_len (int) Maximum String length that can be in this field. Only for String fields.
min_len (int) Minimum String length that can be in this field. Only for String fields.
unique (array) To verify that the field in the table is unique. If it's necessary to check that a field is unique compared to other fields, then they need to be in an array. If this isn't necessary (i.e. we're checking just this one field), then an empty array needs to be set. It's not necessary to put the field that has this option set into the array.
current_table_only (boolean) Checks whether a value in a field is unique in the current table (live or temporary). By default, the field is checked in both the live and temporary tables (if accessible).
required (int, boolean) 'min_value_exc' => 0. Field must be filled in. If a value is not set, then the field will contain an error. Zero as the field value doesn't result in an error saying that the field wasn't filled in. However, if the field value being set to zero should result in an error, it's possible to additionally set an interval for what the value must be, for example 'min_value_exc' => 0.

All of the above described options can be combined into meaningful groups:

  • intervals (max_value_inc, min_value_inc, max_value_exc, min_value_exc) - options used for checking whether a field value falls in the indicated range.
  • length (max_len, min_len) - options used for checking the length of a String.
Image:Tipbox Icon.gif If one or another option is not need, then its declaration can simply be removed from the array of field options, making it not necessary to set its value to 0 or false.

Error Messages

For each field it's possible to set alternative error message text for all error messages by using the option error_msgs (array). The below table describes all standard errors:

Pseudo Description Default Value Controlled by Options
required Field value not filled in. !la_err_required! required
unique Field value not unique. !la_err_unique! unique
value_out_of_range Field value is not within the indicated range !la_err_value_out_of_range! max_value_inc, min_value_inc, max_value_exc, min_value_exc
length_out_of_range String too long. !la_err_length_out_of_range! max_len, min_len
bad_type Field value type isn't the type it's set to be (for example, a character was entered instead of an integer). !la_err_bad_type! type
invalid_format String format isn't as required. !la_err_invalid_format! regexp
bad_date_format Date format isn't as required. !la_err_bad_date_format! опции kDateFormatter
primary_lang_required Field value not entered in primary language. !la_err_primary_lang_required! required, kMultiLanguage Options
bad_file_format Attempt to upload a file whose (mime-type) isn't in the allowed types. !la_error_InvalidFileFormat! allowed_types, опции kUploadFormatter
bad_file_size Attempt to upload a file whose size is greater than allowed maximum size. !la_error_FileTooLarge! max_size, опции kUploadFormatter
cant_save_file File uploaded to the server couldn't be saved to the requested directory. !la_error_cant_save_file! upload_dir, опции kUploadFormatter

This option is set in the form of an associative one-dimensional array, where each key is an error's "pseudo" (see the above table) and each field is the error message.

'error_msgs' => Array (
	'required' => '!la_error_CustomRequiredError!'
)

To make it so that a phrase translation is used as an error message it's name must be enclosed in exclamation marks:

  • "!la_error_ErrorPhrase!" - phrase (it's translation in the current language will be the error message);
  • "Error Message" - text (will be the same for all languages).

Formatter Options

All of the remaining options are processed with specific formatters. Some of them for example are:

Option Name Option Description
formatter (string) Name of the formatter's class. Here are the most common classes:

The specifics about which formatters exist and how to use them can be read in this article.

Automatic Structuring

K4 has a mechanism that automatically builds an array for Fields options. To use it, following these steps:

  • Go to section "Configuration -> System Tools" (in Platform) or "Tools -> System Tools" (in In-Portal);
  • In the field "Table Structure" enter the table name' (without TABLE_PREFIX is ok) or unit config prefix;
  • Press "Go" button;
  • A new window will open with the structure of the table:
Automatically built table structure
Automatically built table structure


Image:Infobox Icon.gif When adding new fields to a table all of the above steps need to be taken, but from the result copy only the needed fields rather than all of them as usual. It's not necessary to write everything by hand.

While building the structure of the fields, the following options are automatically set (if possible to determine):

  • type - PHP data value type that's going to be stored in the field;
  • not_null - NULL or NOT NULL;
  • default - Default value;
  • formatter - Formatter class, for now only for numerical fields (float, double, decimal);
  • max_len - Limit on the length of a field value, only for String fields (varchar).

Functionality available starting with Core v 4.1.0.

Translated from: revision 1072