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
(Working with a single Unit: Trans.)
(Описание работы со списком: Trans)
Line 41: Line 41:
Additionally, "<code>OnItemBuild</code>" 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.
Additionally, "<code>OnItemBuild</code>" 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 ==
-
Для отображения списка компонентов применяется тэг <code>PrintList2</code>. Пример:
+
For displaying a list of Unit records <code>PrintList2</code> tag should be used. For example:
<source lang="xml">
<source lang="xml">
     <inp2:sample_PrintList per_page="-1" render_as="block_name" columns="3" />
     <inp2:sample_PrintList per_page="-1" render_as="block_name" columns="3" />
</source>
</source>
-
Приведённый выше код распечатает все компоненты "<code>sample</code>" внутри таблицы с тремя колонками. Каждая новая строка будет представлена результатом обработки блока "<code>block_name</code>".
 
-
Опция конфига <code>ListSortings</code> позволяет управлять последовательностью, в которой будут выводиться списки. Необходимо указать <code>Special</code>, поля и правила сортировки. Пример:
+
In above code example system will output all records (<code>per_page="-1"</code>) of "<code>sample</code>" Unit inside of html table in 3 columns. Where each new record will be an output from parsing "<code>block_name</code>" block.
 +
 
 +
 
 +
Unit Config option <code>ListSortings</code> allows to control the sorting order for the lists. It's required to specify <code>Special</code>, fields and definitions of the sorting. Example:
<source lang="php">
<source lang="php">
'ListSortings' => Array(
'ListSortings' => Array(
Line 57: Line 59:
),
),
</source>
</source>
-
Параметр <code>ForcedSorting</code> устанавливает принудительную сортировку.
+
Parameter <code>ForcedSorting</code> sets a forced sorting if needed. As you can see in the example above it ca n be used for such fields as <code>Priority</code> or other when you want forcing the sorting.  
-
Параметр конфига <code>TitlePresets</code> управляет различными заголовками в административной части сайта:
+
 
 +
Unit Config option <code>TitlePresets</code> controls different headings in Admin Console of In-Portal:
<source lang="php">
<source lang="php">
'TitlePresets' => Array(
'TitlePresets' => Array(
Line 79: Line 82:
),
),
</source>
</source>
-
<code>#order_recordcount#</code> - такая строка автоматически заменится на количество компонентов <code>order</code> (общее или количество отфильтрованных, если на гриде применены фильтры).
+
<code>#order_recordcount#</code> - this automatically replaced with number of records of <code>order</code> Unit (total or filtered, in case if filters were applied on this grid).
-
 
+
== Гриды ==
== Гриды ==

Revision as of 17:29, 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).

Гриды

Грид - это список компонентов, выводящийся в административной части сайта. Грид предоставляет полную свободу действий над компонентами: просмотр как деталей отдельного компонента, так и сортированного списка всех компонентов, а так же поиска по любому полю.


Редактирование

Редактирование компонента может осуществляться как с пользовательской части сайта, так и из административной. Разница лишь в том, что административная часть уже содержит все необходимые формы и требует только заполнения конфиг файла для компонента.

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

<form id="join_form" method="post" action="<inp2:m_FormAction m_cat_id="0" />" enctype="multipart/form-data">
</form>

Если форма содержит поля для загрузки файлов - обязательно нужно указать параметр enctype="multipart/form-data".

Основные типы полей

В полях компонентов можно хранить информацию самых различных типов. От строковых данных до изображений (фактически, всё же, изображения хранятся в специально отведённом месте, а в поле компонента записана только ссылка на файл изображения). Поля в конфигурации определяются следующим образом:

$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# в качестве значения по-умолчанию, которое будет автоматически заменено на текущую дату при создании компонента.

[1]