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
Line 87: Line 87:
| <code>invalid_format</code> || String format isn't as required. || <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>" ошибок (см. приведённую выше таблицу), а в значениях соответствующие им тексты ошибок:
Эта опция задаётся в виде ассоциативного одномерного массива, в ключах которого указаны "<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 105: 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).
-
== Опции форматера ==
+
== Formatter Options ==
Все оставшиеся опции обрабатываются указанным [[K4:Formatters|форматером]]. Вот, к примеру некоторые из них:
Все оставшиеся опции обрабатываются указанным [[K4:Formatters|форматером]]. Вот, к примеру некоторые из них:

Revision as of 16:46, 26 April 2009

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.

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

Эта опция задаётся в виде ассоциативного одномерного массива, в ключах которого указаны "pseudo" ошибок (см. приведённую выше таблицу), а в значениях соответствующие им тексты ошибок:

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

Все оставшиеся опции обрабатываются указанным форматером. Вот, к примеру некоторые из них:

название опции описание опции
formatter (string) Название класса накладываемого форматера. Вот самые ходовые классы:
  • kFormatter - для обработки чисел, денежных сумм, почтовых адресов
  • kOptionsFormatter - для работы с элементами ограниченного выбора (dropdown, radio buttons и т.п.)
  • kDateFormatter - для обработки дат
  • kUploadFormatter - для загрузки файлов на сервер

Подробнее о том, какие есть форматеры и как их использовать можно прочесть в этой статье.

Автоматическое построение структуры

В K4 есть механизм, который автоматически выстраивает массив для опции Fields. Чтобы воспользоваться им следуйте приведённым шагам:

  • пойти в секцию "Configuration -> System Tools" (в Platform) или "Tools -> System Tools" (в In-Portal);
  • в поле "Table Structure" вписать имя таблицы (можно без TABLE_PREFIX) или префикс от unit config;
  • нажать на кнопку "Go";
  • откроется новое окно со структурой введённой таблицы:
Автоматически построенная структура таблицы
Автоматически построенная структура таблицы


Image:Infobox Icon.gif При добавлении новых полей в таблицу нужно повторить все выше описанные шаги, но из результата скопировать описание только нужных полей, а не всех как обычно. Не надо писать всё руками.

При построении структуры полям автоматически прописываются (если удаётся определить) следующие опции:

  • type - php тип значения, которое будет храниться в поле;
  • not_null - NULL или NOT NULL пометка;
  • default - значение по умолчанию;
  • formatter - класс форматера, пока только для дробный полей (float, double, decimal);
  • max_len - ограничение по длине значения в поле, только для строковых полей (varchar).

Функциональность доступна начиная с Core v 4.1.0.