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:Using "TitlePresets" Option

From In-Portal Developers Guide

Jump to: navigation, search
Unit Configs Unit Configs
Статьи в этой категории

Virtually every page on the site has such an element a Title (title). This is the text in abbreviated form explaining what kind of information is displayed on the page. The title may just be the text, translated depending on the selected language interface, as well as information about the data displayed on the page. For example, if a page displays the пользователя data, then the title is appropriate to show Username of the user. If the page contains a list of orders, then the title can show the number of orders.

Thus, the title page can be composed of a small number of typical elements. This allows in almost all cases use a standard method for formation of the page title, and so the standard way of In-Portal is setting the header by setting the TitlePresets option in Unit Config file and then output using combined_header. This block contains [TagProcessor:SectionTitle|SectionTitle]] tag, which collects all header elements in the string and displays it in a standard, designed specifically for this site way.

Since, the SectionTitle tag is called in combined_header block with pass_params="true" parameter, then through combined_header block can be set any parameters for the SectionTitle tag, except for cut_first, which has already been set within that block.

Contents

How to Define

'TitlePresets' => Array (
	'title_preset_name' => Array (
		'new_status_labels' => Array (),
		'edit_status_labels' => Array (),
		'new_titlefield' => Array (),
 
		'prefixes' => Array (),
		'tag_params' => Array (),		
		'format' => '',
	)
)


In the above example the keys of the first level displayed in summarized/brief form. There is only one "title_preset_name" title. There can be any number of titles, of course, each must have a unique key in the TitlePresets array. It's highly recommended, as a title key to pick a string related to the sense of the pages on which title will be displayed. For example:

  • "user_edit" - for edit template for Users;
  • "denied_order_list" - for list of denied Orders.

Keys

key name description
new_status_labels (array) In this key, each used in the title Unit prefix sets the text to indicate that a new record will be created. This text (usually a phrase if the form "!la_title_AddingOrder!") will later be inserted instead of the "#prefix_status#" code within the value of format key, but only when, a new record is created the database. This is shown in the example below.
'order_edit' => Array (
	'new_status_labels' => Array ('ord' => '!la_title_AddingOrder!'),
	'prefixes' => Array ('ord'), 'format' => '#ord_status#'),
),
Image:Tipbox Icon.gif This key is usually used in conjunction with edit_status_labels and new_titlefield keys to get the most complete forms of creating and editing records.
edit_status_labels (array) In this key, each used in the title Unit prefix sets the text to indicate that currently is editing a previously created record. This text (usually a phrase if the form "!la_title_EditingOrder!") will later be inserted instead of the "#prefix_status#" code within the value of format key, but only when, editing a previously existing in the database record. This is shown in the example below.
'order_edit' => Array (
	'edit_status_labels' => Array ('ord' => '!la_title_EditingOrder!'),
	'prefixes' => Array ('ord'), 'format' => '#ord_status#'),
),
Image:Tipbox Icon.gif This key is usually used in conjunction with edit_status_labels and new_titlefield keys to get the most complete forms of creating and editing records.
new_titlefield (array) In this key, each used in the title Unit prefix sets the text to shown instead of empty field value specified in the TitleField option. This text (usually a phrase if the form "!lla_title_NewOrder!") will later be inserted instead of the "#prefix_titlefield#" code within the value of format key, but only when, a new record is created the database. This is shown in the example below.
'order_edit' => Array (
	'new_titlefield' => Array ('ord' => '!la_title_NewOrder!'),
	'prefixes' => Array ('ord'), 'format' => '#ord_titlefield#'),
),
Image:Tipbox Icon.gif This key is usually used in conjunction with edit_status_labels and new_titlefield keys to get the most complete forms of creating and editing records.
prefixes (array) In this key, given a list of Unit prefixes used to display this title. Note that prefixes for Item object types these are not different are written as it is, but for Unit prefixes with List object of types is appended the word "_List". For example, this is how how prefixes for single Order record and list of archived orders should be defined if both needs to have the same title:
'prefixes' => Array ('ord', 'ord.archived_List')
tag_params (array) This optional key can be used to set initialization parameters for each of the objects used in the title. Initialization of objects occurs at the first call from a kApplication::recallObject method. As the third parameter this method takes an array of initialization parameters "$event_params". This key is just provided to set these parameters if needed. For example, to change (override) specified by the default number of entries displayed per page on the list. For this you can use "per_page" parameter which will be used as described above:
'prefixes' => Array ('conf'),
'tag_params' => Array (
	'conf' => Array (
		'per_page' => -1
	),
),
Image:Infobox Icon.gif Note that in tag_params key exists in an associative array for each Unit prefix, which they need.
format (string) This is the main key which contains a string with all text and other keys listed above, and as result of parsing outputs the actual title. This is kind of pattern of yje title. This string may contain::
  • plain text;
  • language phrases;
  • information about Item type objects used on the page;
    • status of object - adding or editing;
    • value of the field set in TitleField;
    • value of any field;
  • any information about List type objects, used on this page;
    • record counts with filters or without them.

Plain text is displayed as is. Language Phrases - replaced with their translations. All language phrases must be escaped using exclamation marks ! (eg. "!la_title_OrderShipping!". Other elements are escaped with a "#" (ie. #ord.denied_recordcount#).

toolbar_buttons (array) In this key are listed buttons names (without the module, ie. "sample_button", not "custom:sample_button") that will be used on the toolbar, and can be hidden with Site Configs functionality. This is shown in the example below:
'toolbar_buttons' => Array ('new_item', 'edit', 'delete', 'view'),

Available since In-Portal v 5.0.0.

Special Functionality of "format" Key

name description
#prefix[.special]_status# Данный код заменится на текст, заданный в массиве ключа new_status_labels, если объект находится в статусе "новый" (его ID <= 0) и на текст, заданный в массиве ключа edit_status_labels во всех остальных случаях. Эти ключи задаются с указанием префиксов в качестве ключей подмассива:
'new_status_labels' => Array ('ord' => '!la_title_AddingOrder!'),
'edit_status_labels' => Array ('ord' => '!la_title_EditingOrder!'),
'prefixes' => Array ('ord'), 'format' => '#ord_status#'),
#prefix[.special]_titlefield# Данный код замениться на значение поля, определённого в конфигурации соответствующего префикса как TitleField. Подробнее это будет видно на ниже приведённом примере.
'prefixes' => Array ('ord'), 'format' => "#ord_titlefield#' - !la_title_General!",

В результате выполнения выше приведённого примера в заголовке будет показано значение поля, заданного в ключе TitleField у префикса ord, то есть, поле OrderNumber от текущего заказа.

Может случиться, что открыт шаблон создания записи, и поле, заданное в ключе TitleField у префикса имеет пустое значение. Для того, чтобы и в этом случае заголовок страницы выглядел содержательным, можно настроить ключ new_titlefield. Таким образом обеспечивается что код вида "#prefix[.special]_titlefield#" никогда не превратится в пустоту. Подробнее это будет видно на ниже приведённом примере.

'new_titlefield' => Array ('ord' => '!la_title_NewOrder!')
#prefix[.special]_<FieldName># Также присутствует возможность вывести значение любого поля объекта указав его следующим образом: "#prefix[.special]_FieldName#". В ниже приведённом примере будет отображено значение поля OrderNumber текущего заказа.
'format' => "#ord_status# '#ord_OrderNumber#' - !la_title_General!"
#prefix[.special]_recordcount# Когда для заголовка настроен объект типа List, то в заголовке можно показать количество записей. Подробнее это будет видно на ниже приведённом примере.
'prefixes' => Array ('ord.denied_List'),
'format' => "!la_title_OrdersDenied! (#ord.denied_recordcount#)"

Когда в списке нет фильтров, этот код заменится на количество записей. Если же фильтры имеются, то код заменится на строку, включающую количество записей с фильтром и количество записей без фильтра, например: "25 of 79".

#section_label# Данный код замениться на перевод опции label в описании секции, переданной в параметре section блока combined_header, который в итоге и будет показывать title preset. Это будет показано на ниже приведённом примере.
'format' => "#section_label#"

Данный формат доступен начиная с Core v 5.0.0.

Заголовок "default"

Также есть специальный заголовок "default", данные которого будут автоматически скопированы в каждый созданный заголовок. Его можно использовать для конфигурации элементов, повторяющихся в прочих заголовках. Например, такую конфигурацию, где все заголовки настроены одинаково, кроме ключа format:

'TitlePresets' => Array (
	'order_edit_general' => Array (
		'new_status_labels' => Array ('ord' => '!la_title_AddingOrder!'),
		'edit_status_labels' => Array ('ord' => '!la_title_EditingOrder!'),
		'new_titlefield' => Array ('ord' => '!la_title_NewOrder!'),
 
		'prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_General!"
	),
 
	'order_edit_billing' => Array (
		'new_status_labels' => Array ('ord' => '!la_title_AddingOrder!'),
		'edit_status_labels' => Array ('ord' => '!la_title_EditingOrder!'),
		'new_titlefield' => Array ('ord' => '!la_title_NewOrder!'),
 
		'prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderBilling!",
	),
 
	'order_edit_shipping' => Array (
		'new_status_labels' => Array ('ord' => '!la_title_AddingOrder!'),
		'edit_status_labels' => Array ('ord' => '!la_title_EditingOrder!'),
		'new_titlefield' => Array ('ord' => '!la_title_NewOrder!'),
 
		'prefixes' => Array ('ord'), 'format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderShipping!"
	),
),

можно заменить эквивалентной конфигурацией, убрав повторяющиеся настройки в ключ default:

'TitlePresets' => Array (
	'default' => Array (	
		'new_status_labels' => Array ('ord' => '!la_title_AddingOrder!'),
		'edit_status_labels' => Array ('ord' => '!la_title_EditingOrder!'),
		'new_titlefield' => Array ('ord' => '!la_title_NewOrder!'),
 
		'prefixes' => Array ('ord'), 
	),
 
	'orders_edit_general' => Array ('format' => "#ord_status# '#ord_titlefield#' - !la_title_General!"),
	'orders_edit_billing' => Array ('format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderBilling!"),
	'orders_edit_shipping' => Array ('format' => "#ord_status# '#ord_titlefield#' - !la_title_OrderShipping!"),
),

Избегая с помощью ключа default дублирования кода, облегчаются последующие изменения - изменения придётся делать только в одном месте.

Примеры использования

Заголовки в In-Portal и платформы формируются по одной схеме, но в платформе имеется 3 основных отличия:

  • не используется ключ new_titlefield;
  • не используется конструкция "#prefix[.special]_recordcount#" (т.к. её результат уже виден под списком);
  • для главных префиксов не задаются заголовки (т.к. в них только и показывается количество записей из предыдущего пункта).

Список главного префикса

Конфигурация:

'product_list' => Array ('prefixes' => Array ('p_List'), 'format' => "!la_title_Products! (#p_recordcount#)")

Код в шаблоне:

<inp2:m_RenderElement name="combined_header" prefix="p" section="in-commerce:products" title_preset="product_list"/>
Image:Tipbox Icon.gif Для платформы заголовок списка главного префикса не задаётся и не используется.

Редактирование главного префикса

Конфигурация:

'default' => Array (
	'new_status_labels' => Array ('p' => '!la_title_AddingProduct!'),
	'edit_status_labels' => Array ('p' => '!la_title_EditingProduct!'),
	'new_titlefield' => Array ('p' => '!la_title_NewProduct!'),
),
 
'product_edit' => Array ('prefixes' => Array ('p'), 'format' => "#p_status# '#p_titlefield#' - !la_title_General!"),

Код в шаблоне:

<inp2:m_RenderElement name="combined_header" prefix="p" section="in-commerce:products" title_preset="product_edit"/>
Image:Tipbox Icon.gif Для платформы убирается код, содежащий "'new_titlefield'".

Список подчинённого префикса

Конфигурация:

'default' => Array (
	'new_status_labels' => Array ('p' => '!la_title_AddingProduct!'),
	'edit_status_labels' => Array ('p' => '!la_title_EditingProduct!'),
	'new_titlefield' => Array ('p' => '!la_title_NewProduct!'),
),
 
'image_list' => Array ('prefixes' => Array ('p', 'img_List'), 'format' => "#p_status# '#p_titlefield#' - !la_title_Images! (#img_recordcount#)"),

Код в шаблоне:

<inp2:m_RenderElement name="combined_header" prefix="p" section="in-commerce:products" title_preset="image_list"/>
Image:Tipbox Icon.gif Для платформы убирается " (#img_recordcount#)" из значения ключа format и код, содежащий "'new_titlefield'".

Редактивание подчинённого префикса

Конфигурация:

'default' => Array (
	'new_status_labels' => Array ('p' => '!la_title_AddingProduct!'),
	'edit_status_labels' => Array ('p' => '!la_title_EditingProduct!'),
	'new_titlefield' => Array ('p' => '!la_title_NewProduct!'),
),
 
'image_edit' => Array (
	'new_status_labels' => Array ('img' => '!la_title_AddingImage!'),
	'edit_status_labels' => Array ('img' => '!la_title_EditingImage!'),
	'new_titlefield' => Array ('img' => '!la_title_NewImage!'),
 
	'prefixes' => Array ('p', 'img'), 'format' => "#p_status# '#p_titlefield#' - #img_status# '#img_titlefield#'",
)

Код в шаблоне:

<inp2:m_RenderElement name="combined_header" prefix="p" section="in-commerce:products" title_preset="image_edit"/>
Image:Tipbox Icon.gif Для платформы убирается код, содежащий "'new_titlefield'".


Translated from: revision 1077