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:Event Handlers

From In-Portal Developers Guide

Jump to: navigation, search
Current revision (18:46, 28 November 2010) (view source)
(Trans.)
 
Line 1: Line 1:
{{toc | category = Обработчик событий | sortkey = 001.001}}
{{toc | category = Обработчик событий | sortkey = 001.001}}
-
Обработчики событий позволяют выполнять действия на основании данных пользователя, попадающих в PHP через специальным образом сформированные запросы на сервер. Ниже приведены основные аспекты написания обработчиков событий, которые призваны помочь с минимальными усилиями написать требуемый обработчик события.
+
The purpose of Event handlers is to handle and process user data submitted through website and passed to PHP. Below you will see the main aspects of programming the event handlers.
-
== Получение объекта, участника события ==
+
== Getting Object of Event Caller ==
-
* Если известно, что ID объекта доступно в запросе пользователя, то нужно использовать следующий код:
+
* Following code should be used if the object ID is passed in request submitted by the user:
<source lang="php">
<source lang="php">
$object =& $event->getObject();
$object =& $event->getObject();
</source>
</source>
-
Этот код не только получит объект, но и загрузит в него данные по ID найденному в запросе пользователя.  
+
Additionally, this code will load the actual object data using the ID passed in user request.
-
* Если про ID объекта ничего не известно, то нужно использовать следующий код:
+
* Following code should be used if object ID is unknown:
<source lang="php">
<source lang="php">
$object =& $event->getObject( Array('skip_autoload' => true) );
$object =& $event->getObject( Array('skip_autoload' => true) );
</source>
</source>
-
Такой подход использован в событиях <code>OnCreate</code> и <code>OnUpdate</code>, т.к. в первом из них ID нету вообще, а втором может быть за раз передано более одного ID.
+
This approach is used by <code>OnCreate</code> and <code>OnUpdate</code> events because first one doesn't have an ID (adding new data record), while second can receive more then one (1) object ID at the same time (ie. when you are editing multiple data records).
-
== Получение данных из формы ==
+
== Getting Form Data ==
-
Получить данные из формы (только в случае, если был использован POST запрос) можно использовав следующий код:  
+
*Following code gets the data submitted through the form (only in case if POST request is used):
<source lang="php">
<source lang="php">
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );
</source>
</source>
-
== Обработка данных из формы ==
+
== Processing Form Data ==
-
* В случае, если передано только одно ID, то массив <code>$items_info</code> (см. пример [[#Получение данных из формы|Получение данных из формы]]) нужно использовать следующим образом:
+
* In case if only object ID has been passed through the form then <code>$items_info</code> array (see. [[#Getting Form Data|Getting Form Data]]) should be used in the following manner:
<source lang="php">
<source lang="php">
if ($items_info) {
if ($items_info) {
list ($id, $field_values) = each($items_info);
list ($id, $field_values) = each($items_info);
-
// обработка данных
+
// data processing
}
}
</source>
</source>
-
* В случае, когда из запроса могут быть получены данные сразу нескольких объектов, то нужно использовать следующий код:
+
* In case if request can have multiple object IDs passed, then it's recommended to use the following code:ледующий код:
<source lang="php">
<source lang="php">
if ($items_info) {
if ($items_info) {
foreach ($items_info as $id => $field_values) {
foreach ($items_info as $id => $field_values) {
-
// обработка данных
+
// data processing
}
}
}
}
</source>
</source>
-
== Указание шаблона для перенаправления ==
+
== Specifying Redirect Template ==
-
После успешного выполнения обработчика события автоматически происходит перенаправление на текущий шаблон (на Front-End) или на шаблон со списком, из которого был открыт данный шаблон (в Admin). Если требуется указать шаблон, отличный от шаблона подставляемого автоматически нужно использовать атрибут <code>redirect</code> объекта <code>$event</code>:
+
Right after successful execution and processing of called event, a redirect to current template (if Front-End) or last data grid (in Admin) will take place. In case if custom redirect template needs to be specified, then <code>redirect</code> property of the object should be used:<code>$event</code>:
<source lang="php">
<source lang="php">
-
$event->redirect = 'template_name';
+
$event->redirect = 'template_name'; // in-link/links/thankyou
</source>
</source>
-
{{TipBox|Название шаблонов для перенаправления не следует "зашивать" (hardcoded) в коде. Их лучше всего передавать из формы, в которой было вызвано событие.}}
+
{{TipBox|Note that it's a bad practice to hard-code any template names in your PHP code. The best solution would be to pass it through the form which called actual event.}}
-
На данный момент механизм работы с всплывающими окнами (popups) построен таким образом, что значение атрибута <code>redirect</code> будет проигнорировано. Независимо от этого на Front-End будет учитываться значение данного атрибута. Но надо отметить, что если будет нужно изменить шаблон для перенаправления у событий <code>OnCreate</code> или <code>OnUpdate</code>, то нужно перед присваиванием шаблона выполнить следующий код:
+
 
 +
 
 +
Current pop-up functionality in Admin Console is build in such way that value of <code>redirect</code> property will ignored. Regardless of that Front-End will always use that property. In case if it's needed to change the redirect template for <code>OnCreate</code> or <code>OnUpdate</code> events, then the following code should be used before setting a new value into <code>redirect</code> property.:
<source lang="php">
<source lang="php">
$event->SetRedirectParam('opener', 's');
$event->SetRedirectParam('opener', 's');
</source>
</source>
-
Если используются другие обработчики событий, то этого делать не нужно.
+
It's not required if other Events are used.
-
== Вызов нового события из обработчика событий ==
+
== Calling New Event from Event Handler ==
-
* Для вызова нового события с таким же [[K4:Unit Configs#Prefix|префиксом]], как у текущего события (откуда выполняется код) нужно написать следующий код:
+
Following code should be used to call a new event of the same [[K4:Unit Configs#Prefix|Unit prefix]] (in other words the same unit):
<source lang="php">
<source lang="php">
$event->CallSubEvent('OnSampleEvent');
$event->CallSubEvent('OnSampleEvent');
</source>
</source>
-
* Для вызова события у которого [[K4:Unit Configs#Prefix|префикс]] отличается от текущего нужно написать следующий код:
+
 
 +
Following code should be used to call a new event of different [[K4:Unit Configs#Prefix|Unit prefix]]:
<source lang="php">
<source lang="php">
$this->Application->HandleEvent( new kEvent('prefix.special:OnSampleEvent') );
$this->Application->HandleEvent( new kEvent('prefix.special:OnSampleEvent') );
</source>
</source>
-
{{TipBox|Если special не используется, то и точку ставить не надо.}}
+
{{TipBox|No need to put a dot (.) if no special been used.}}
-
== Сопоставление прав доступа и обработчика события ==
+
== Specifying Permissions for Event Handlers ==
-
Если пишется обработчик события, которое не описано в классе <code>kDBEventHandler</code>, то права доступа, необходимые для выполнения данного события нужно указать в методе <code>kEventHandler::mapPermissions</code>:
+
When you are creating a new event handler which is not part <code>kDBEventHandler</code> class, then access permissions must be specified in <code>kEventHandler::mapPermissions</code> method for you custom event handler to properly execute::
<source lang="php">
<source lang="php">
function mapPermissions()
function mapPermissions()
Line 74: Line 77:
}
}
</source>
</source>
-
Если в [[K4:Unit Configs|unit config]], в котором указан класс, содержащий обработчик события находиться опция [[K4:Unit Configs#SubItems|SubItems]], то названия прав доступа нужно указывать в ключе "<code>self</code>". Если такой опции нету, то названия прав доступа нужно указывать в ключе "<code>subitem</code>". Если требуется указать несколько прав доступа одновременно, то нужно их разделять используя вертикальную черту ("<code>|</code>"). В таком случае у пользователя будет проверяться наличие хотя бы одного из перечисленных прав. Если для выполнения события никакие права не нужны, то нужно указать "<code>true</code>" вместо строки с названиями прав.
+
 
-
{{InfoBox|В методе <code>mapPermissions</code> запрещается использовать [[K4:Стиль программирования#Управляющие структуры|управляющие структуры]].}}
+
If the [[K4:Unit Configs|Unit Config]], which declared the class of that event handler has an [K4:Unit Configs#SubItems|SubItems]] option, then the name of the access rights must be specified in the "<code>self</ code>" key. If this option is not present, then the name of the access rights must be specified in "<code>subitem</ code>" key. If you want to specify multiple access rights at the same time, you need to separate them using a vertical bar ("<code> | </ code>"). In this case, the user will be checked to have at least one of these rights. If event execution requires no permission check at all, then you can simply specify "<code>true</ code>" instead of a string with permission names.
 +
{{InfoBox|It's prohibited to use any [[K4:Стиль программирования#Управляющие структуры|Control Structures]] in <code>mapPermissions</code> method.}}
 +
 
 +
[[en:{{FULLPAGENAME}}]]
 +
[[ru:K4:Обработчики событий]]
 +
 
 +
 
 +
 
 +
Translated from: [http://guide.in-portal.org/rus/index.php?title=K4:%D0%9E%D0%B1%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%87%D0%B8%D0%BA%D0%B8_%D1%81%D0%BE%D0%B1%D1%8B%D1%82%D0%B8%D0%B9&oldid=1076 revision 1076]

Current revision

Обработчик событий Обработчик событий
Статьи в этой категории
  • Event Handlers

The purpose of Event handlers is to handle and process user data submitted through website and passed to PHP. Below you will see the main aspects of programming the event handlers.

Contents

Getting Object of Event Caller

  • Following code should be used if the object ID is passed in request submitted by the user:
$object =& $event->getObject();

Additionally, this code will load the actual object data using the ID passed in user request.

  • Following code should be used if object ID is unknown:
$object =& $event->getObject( Array('skip_autoload' => true) );

This approach is used by OnCreate and OnUpdate events because first one doesn't have an ID (adding new data record), while second can receive more then one (1) object ID at the same time (ie. when you are editing multiple data records).

Getting Form Data

  • Following code gets the data submitted through the form (only in case if POST request is used):
$items_info = $this->Application->GetVar( $event->getPrefixSpecial(true) );

Processing Form Data

  • In case if only object ID has been passed through the form then $items_info array (see. Getting Form Data) should be used in the following manner:
if ($items_info) {
	list ($id, $field_values) = each($items_info);
	// data processing
}
  • In case if request can have multiple object IDs passed, then it's recommended to use the following code:ледующий код:
if ($items_info) {
	foreach ($items_info as $id => $field_values) {
		// data processing
	}
}

Specifying Redirect Template

Right after successful execution and processing of called event, a redirect to current template (if Front-End) or last data grid (in Admin) will take place. In case if custom redirect template needs to be specified, then redirect property of the object should be used:$event:

$event->redirect = 'template_name'; // in-link/links/thankyou
Image:Tipbox Icon.gif Note that it's a bad practice to hard-code any template names in your PHP code. The best solution would be to pass it through the form which called actual event.


Current pop-up functionality in Admin Console is build in such way that value of redirect property will ignored. Regardless of that Front-End will always use that property. In case if it's needed to change the redirect template for OnCreate or OnUpdate events, then the following code should be used before setting a new value into redirect property.:

$event->SetRedirectParam('opener', 's');

It's not required if other Events are used.

Calling New Event from Event Handler

Following code should be used to call a new event of the same Unit prefix (in other words the same unit):

$event->CallSubEvent('OnSampleEvent');

Following code should be used to call a new event of different Unit prefix:

$this->Application->HandleEvent( new kEvent('prefix.special:OnSampleEvent') );
Image:Tipbox Icon.gif No need to put a dot (.) if no special been used.

Specifying Permissions for Event Handlers

When you are creating a new event handler which is not part kDBEventHandler class, then access permissions must be specified in kEventHandler::mapPermissions method for you custom event handler to properly execute::

function mapPermissions()
{
	parent::mapPermissions();
	$permissions = Array (
		'OnSampleEvent' => Array ('self' => 'main_permissions', 'subitem' => 'subitem_permissions'),		
	);
 
	$this->permMapping = array_merge($this->permMapping, $permissions);
}

If the Unit Config, which declared the class of that event handler has an [K4:Unit Configs#SubItems|SubItems]] option, then the name of the access rights must be specified in the "self</ code>" key. If this option is not present, then the name of the access rights must be specified in "<code>subitem</ code>" key. If you want to specify multiple access rights at the same time, you need to separate them using a vertical bar ("<code> | </ code>"). In this case, the user will be checked to have at least one of these rights. If event execution requires no permission check at all, then you can simply specify "<code>true</ code>" instead of a string with permission names.

Image:Infobox Icon.gif It's prohibited to use any Control Structures in <code>mapPermissions</code> method.


Translated from: revision 1076