K4:Purpose and Usage of Units
From In-Portal Developers Guide
(→Гриды: Trans) |
(→Редактирование: Trans) |
||
Line 87: | Line 87: | ||
Grid - is a list of records of a Unit shown in Admin Console. The main advantage of Grids is that they provide the complete flexibility and control of the records: ability to see any data fields of the Unit, sorting and search by any of the fields at the same time. | Grid - is a list of records of a Unit shown in Admin Console. The main advantage of Grids is that they provide the complete flexibility and control of the records: ability to see any data fields of the Unit, sorting and search by any of the fields at the same time. | ||
- | == | + | == Data Editing == |
- | + | Data editing can be done via both - Admin Console or Front-End. The main difference is that Admin already has all required data forms and you just need to properly setup a Unit Config file with fields that you need for data storing. | |
- | + | However, in order to edit the data record from the Front-End you need to setup a form with fields that will be updated during the editing and pass the Event name that will process the data update (ie. <code>"OnUpdate"</code>). Example: | |
<source lang="xml"> | <source lang="xml"> | ||
<form id="join_form" method="post" action="<inp2:m_FormAction m_cat_id="0" />" enctype="multipart/form-data"> | <form id="join_form" method="post" action="<inp2:m_FormAction m_cat_id="0" />" enctype="multipart/form-data"> | ||
</form> | </form> | ||
</source> | </source> | ||
- | + | Please note that it's required to have <code>enctype="multipart/form-data"</code> parameter if your form contains any file fields. | |
== Основные типы полей == | == Основные типы полей == |
Revision as of 18:17, 27 November 2010
This article is not finished yet! You see this message because current Article is finished yet or contains unverified information. How to write an Article. |
| ||
---|---|---|
Статьи в этой категории | ||
|
Contents |
What are Units
Unit is a single component for storing information in In-Portal
. Unit consist of set of Fields used for storing information and processing it (defined in unit configuration file), set of Tags used specifically by this unit, and set of specific Events used for processing the business logic in this unit.
Each unit can have virtually unlimited number of fields. Fields can be imagined as cells for storing information about different properties of this unit. For example, if we need to build functionality for a guest book using unit approach, it would look like this:
Unit would be called "message" with fields "author", "date of comment", "message" (actual text message).
What can be done with Units
Units can be used to store, process and output the information.
The Class containing unit specific tags extends the base kDBTagProcessor
class which already contains most of the commonly used tags. However, in some cases when it's required to add a new tag or change the behavior of already existing tag and most importantly the change should be limited to a specific Unit - this is when changes should be done in unit specific Tags class. As a result, these new changes won't affect the behavior of the same tags in other Units.
Working with a single Unit
Output of Unit data on template:
<inp2:sample_Field name="Title" />
Above example outputs the content of "Title
" field. Note that this code will work only in case if the page already has loaded object of "sample
" unit or it's ID used for auto-loading has been passed through.
Auto-loading is a process of automatic loading of the Unit by it's ID (identifier). For example, if we used POST
or GET
methods to pass a "sample_id
" variable to the page, then the above code will execute successfully. The goal of auto-loading is require no additional work in order to start working with the object since it will be loaded automatically by ID (identifier).
Creating a new instance of a Unit by calling "OnCreate
" event.
It's important to know that by default the creation of new instances of Unit is prohibited for all users on the Front-End. In order to allow user to create a new instance of the unit a "OnCreate
" event should be listed as publicly available permission in the Unit Event Handler. Below is an example of how it's done:
function mapPermissions() { parent::mapPermissions(); $permissions = Array( 'OnCreate' => Array('self' => true), ); $this->permMapping = array_merge($this->permMapping, $permissions); }
Additionally, "OnItemBuild
" event should be added as publicly available permissions in order to allow loading of the actual Unit object and output of Unit tags on the Front-End.
Working with Unit Lists
For displaying a list of Unit records PrintList2
tag should be used. For example:
<inp2:sample_PrintList per_page="-1" render_as="block_name" columns="3" />
In above code example system will output all records (per_page="-1"
) of "sample
" Unit inside of html table in 3 columns. Where each new record will be an output from parsing "block_name
" block.
Unit Config option ListSortings
allows to control the sorting order for the lists. It's required to specify Special
, fields and definitions of the sorting. Example:
'ListSortings' => Array( '' => Array( 'ForcedSorting' => Array('Priority' => 'desc'), 'Sorting' => Array('OrderDate' => 'desc'), ) ),
Parameter ForcedSorting
sets a forced sorting if needed. As you can see in the example above it ca n be used for such fields as Priority
or other when you want forcing the sorting.
Unit Config option TitlePresets
controls different headings in Admin Console of In-Portal:
'TitlePresets' => Array( 'default' => Array( 'new_status_labels' => Array( 'order' => '!la_title_AddingOrder!' ), 'edit_status_labels' => Array( 'order' => '!la_title_DetailsOfOrder!' ), 'new_titlefield' => Array( 'order' => '!la_title_NewOrder!' ), ), 'order_list'=>Array( 'prefixes' => Array('order_List'), 'format' => "!la_title_purchases! (#order_recordcount#)", ), 'order_edit'=>Array( 'prefixes' => Array('order'), 'format' => "#order_status# #order_titlefield# - !la_title_General!", ), ),
#order_recordcount#
- this automatically replaced with number of records of order
Unit (total or filtered, in case if filters were applied on this grid).
Admin Grids
Grid - is a list of records of a Unit shown in Admin Console. The main advantage of Grids is that they provide the complete flexibility and control of the records: ability to see any data fields of the Unit, sorting and search by any of the fields at the same time.
Data Editing
Data editing can be done via both - Admin Console or Front-End. The main difference is that Admin already has all required data forms and you just need to properly setup a Unit Config file with fields that you need for data storing.
However, in order to edit the data record from the Front-End you need to setup a form with fields that will be updated during the editing and pass the Event name that will process the data update (ie. "OnUpdate"
). Example:
<form id="join_form" method="post" action="<inp2:m_FormAction m_cat_id="0" />" enctype="multipart/form-data">
</form>
Please note that it's required to have enctype="multipart/form-data"
parameter if your form contains any file fields.
Основные типы полей
В полях компонентов можно хранить информацию самых различных типов. От строковых данных до изображений (фактически, всё же, изображения хранятся в специально отведённом месте, а в поле компонента записана только ссылка на файл изображения). Поля в конфигурации определяются следующим образом:
$config = Array( 'Fields' => Array( 'Title' => Array('type' => 'string', 'not_null' => 1, 'default' => '', 'max_len' => 255) ) )
В примере выше показана общая схема составления конфигурации полей. Ключ конфигурационного массива Fields
указывает на то, что начинается декларация полей компонента. Сам массив Fields
является ассоциативным и каждый ключ в нём является названием описываемого поля в базе данных (имена полей регистрозависимы и должны совпадать в шаблонах и в конфигурационном файле!). Массив 3-его уровня является описанием поля и перечисляет все его свойства и особенности. Далее в примерах будет приводиться только этот массив.
Текст
Пример определения текстового поля в конфигурационном файле компонента:
Array('type' => 'string', 'not_null' => 1, 'default' => '', 'max_len' => 255)
Таким массивом описывается простое текстовое поле. Обратите внимание на значение max_len
, если этот параметр не указан - то в поле можно потенциально записать строку неограниченной длинны (т.е. потенциально она может не поместиться в отведённое для неё место в базе данных).
Дата
Пример определения поля с датой в конфигурационном файле компонента:
Array('type' => 'int', 'formatter' => 'kDateFormatter', 'not_null' => 1, 'default' => '#NOW#')
Дата хранится в виде timestamp
, поэтому в базе необходимо поле для хранения целых чисел (длиной 11 символов). Обязательный в этом случае параметр formatter
, указывающий каким форматтером будет обрабатываться поле (для даты - kDateFormatter
). И ключевое слово #NOW# в качестве значения по-умолчанию, которое будет автоматически заменено на текущую дату при создании компонента.