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:Purpose and Usage of Units

From In-Portal Developers Guide

(Difference between revisions)
Jump to: navigation, search
(Редактирование: Trans)
(Основные типы полей: Trans)
Line 97: Line 97:
Please note that it's required to have <code>enctype="multipart/form-data"</code> parameter if your form contains any file fields.
Please note that it's required to have <code>enctype="multipart/form-data"</code> parameter if your form contains any file fields.
-
== Основные типы полей ==
+
== Basic Field Types ==
-
В полях компонентов можно хранить информацию самых различных типов. От строковых данных до изображений (фактически, всё же, изображения хранятся в специально отведённом месте, а в поле компонента записана только ссылка на файл изображения).
+
Unit data fields can used to store different types of information. This can be strings, numbers, text or images (actual images are stored separately in the dedicated places).
-
Поля в конфигурации определяются следующим образом:
+
 
 +
Data Fields in Unit Config file should be defined as follows:
<source lang="php">
<source lang="php">
$config = Array(
$config = Array(
Line 107: Line 108:
)
)
</source>
</source>
-
В примере выше показана общая схема составления конфигурации полей. Ключ конфигурационного массива <code>Fields</code> указывает на то, что начинается декларация полей компонента. Сам массив <code>Fields</code> является ассоциативным и каждый ключ в нём является названием описываемого поля в базе данных (имена полей регистрозависимы и должны совпадать в шаблонах и в конфигурационном файле!). Массив 3-его уровня является описанием поля и перечисляет все его свойства и особенности. Далее в примерах будет приводиться только этот массив.
+
In the example above you can see the general pattern for fields configuration. The <code>Fields</code> key of configuration array indicates that Unit data fields will be defined next. The actual <code>Fields</code> array is an associated array where each key is a name of the data field in the Database. Please note that field names are case sensitives and should match in all places are being used - Unit Config, Database, Templates and PHP code. The array of 3rd level is the actual definition of the field and lists it's type and properties. In below examples only 3rd level array will be used to demonstrate the actual field definitions.
-
=== Текст ===
+
=== Text type ===
-
Пример определения текстового поля в конфигурационном файле компонента:
+
Example of defining a Text field in Unit Config file:
<source lang="php">
<source lang="php">
Array('type' => 'string', 'not_null' => 1, 'default' => '', 'max_len' => 255)
Array('type' => 'string', 'not_null' => 1, 'default' => '', 'max_len' => 255)
</source>
</source>
-
Таким массивом описывается простое текстовое поле. Обратите внимание на значение <code>max_len</code>, если этот параметр не указан - то в поле можно потенциально записать строку неограниченной длинны (т.е. потенциально она может не поместиться в отведённое для неё место в базе данных).
+
This is how a simple text field is defined. Note that <code>max_len</code> parameter limits the length size of this text field. There will be no limit in the length if this field is skipped and text can be virtually of any length/size (keep in mind that actual database field needs the correct size as well in order to fit the data).
-
=== Дата ===
+
=== Date type ===
-
Пример определения поля с датой в конфигурационном файле компонента:
+
Example of defining a Date field in Unit Config file:
<source lang="php">
<source lang="php">
Array('type' => 'int', 'formatter' => 'kDateFormatter', 'not_null' => 1, 'default' => '#NOW#')
Array('type' => 'int', 'formatter' => 'kDateFormatter', 'not_null' => 1, 'default' => '#NOW#')
</source>
</source>
-
Дата хранится в виде <code>timestamp</code>, поэтому в базе необходимо поле для хранения целых чисел (длиной 11 символов). Обязательный в этом случае параметр <code>formatter</code>, указывающий каким форматтером будет обрабатываться поле (для даты - <code>kDateFormatter</code>). И ключевое слово #NOW# в качестве значения по-умолчанию, которое будет автоматически заменено на текущую дату при создании компонента.
+
Dates are stored in <code>timestamp</code> format so these database fields should be INT format with 11 numbers length. Note that <code>formatter</code> param is required in this case since it indicates which formatter system will be using to parse and output the data in this field. The <code>default</code> key with <code>#NOW#</code> value in this array indicates that field will be populated with the current date/time.
[[en:{{FULLPAGENAME}}]]
[[en:{{FULLPAGENAME}}]]
[[ru:K4:Применение Компонентов]]
[[ru:K4:Применение Компонентов]]
-
[http://guide.in-portal.org/rus/index.php?title=K4:%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5_%D0%9A%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D0%BE%D0%B2&oldid=1034]
+
[http://guide.in-portal.org/rus/index.php?title=K4:%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D0%BD%D0%B5%D0%BD%D0%B8%D0%B5_%D0%9A%D0%BE%D0%BC%D0%BF%D0%BE%D0%BD%D0%B5%D0%BD%D1%82%D0%BE%D0%B2&oldid=1034 K4:Применение Компонентов (version1034)]

Revision as of 19:12, 27 November 2010


Компоненты Компоненты
Статьи в этой категории

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.

Basic Field Types

Unit data fields can used to store different types of information. This can be strings, numbers, text or images (actual images are stored separately in the dedicated places).

Data Fields in Unit Config file should be defined as follows:

$config = Array(
	'Fields' => Array(
		'Title' => Array('type' => 'string', 'not_null' => 1, 'default' => '', 'max_len' => 255)
	)
)

In the example above you can see the general pattern for fields configuration. The Fields key of configuration array indicates that Unit data fields will be defined next. The actual Fields array is an associated array where each key is a name of the data field in the Database. Please note that field names are case sensitives and should match in all places are being used - Unit Config, Database, Templates and PHP code. The array of 3rd level is the actual definition of the field and lists it's type and properties. In below examples only 3rd level array will be used to demonstrate the actual field definitions.

Text type

Example of defining a Text field in Unit Config file:

Array('type' => 'string', 'not_null' => 1, 'default' => '', 'max_len' => 255)

This is how a simple text field is defined. Note that max_len parameter limits the length size of this text field. There will be no limit in the length if this field is skipped and text can be virtually of any length/size (keep in mind that actual database field needs the correct size as well in order to fit the data).

Date type

Example of defining a Date field in Unit Config file:

Array('type' => 'int', 'formatter' => 'kDateFormatter', 'not_null' => 1, 'default' => '#NOW#')

Dates are stored in timestamp format so these database fields should be INT format with 11 numbers length. Note that formatter param is required in this case since it indicates which formatter system will be using to parse and output the data in this field. The default key with #NOW# value in this array indicates that field will be populated with the current date/time.

K4:Применение Компонентов (version1034)