Page and media selectors for page builder components

The page and media selectors are system form components that enable users to select pages from a site’s content tree or media files from a site’s media libraries. Each selector returns a collection of identifiers representing the chosen items. You can use these identifiers to access objects in the logic of your page builder components. For example, when developing a widget that displays links to a set of pages on a website, a property that allows editors to configure the linked pages could use the page selector form components.

As well as using the selectors in the administration interface as standard form components (when building properties dialogs of page builder components), you can also use a JavaScript API utilizing the system’s modal dialog support to offer identical functionality anywhere within the code of your components.

The first section of this page describes form components that can be used to facilitate page and media file selection in properties dialogs of page builder components. The second section introduces alternative JavaScript APIs with identical functionality intended for the development of custom page builder components.

You can examine an implementation of a sample widget using selector form components in the LearningKit project on GitHub.

Selector form components

Form components for use in the page builder

The Media, Page, and Path selectors are intended to facilitate page builder component development. These form components are not meant to be used on the live site or as part of any form builder components.

Media files selector

The media files selector form component enables users to select files from a site’s media libraries using an intuitive interface. The selector returns a collection of MediaFilesSelectorItem objects, which contain the GUID of the selected media file in the FileGuid property.

Media files selector interface

The media files selector form component has the following configurable properties:

Property

Type

Description

LibraryName

string

Configures the (single) media library from which you can select files in the selector. If not specified, the selector allows selecting from all media libraries on the current site for which the user has permissions.

MaxFilesLimit

int

Configures the maximum number of files allowed to be selected:

  • 0 – no limit.
  • n – at most n files can be selected at once.

If not specified, the selector allows single file selection by default.

AllowedExtensions

string

A semicolon-delimited string of file extensions that specify the allowed file extensions for the files to be selected. The listed extensions need to form a subset of allowed extensions specified in the Media file allowed extensions site settings key. 

If not specified, the selector uses the extensions from the site settings key by default.

The following example shows the declaration of a property in a page builder component’s property model class that has the MediaFilesSelector form component assigned as its editing component. A URL of the selected image is then retrieved in the corresponding component’s controller.

Component's model class



// Assigns a selector component to the 'Images' property
[EditingComponent(MediaFilesSelector.IDENTIFIER)]
// Configures the media library from which you can select files in the selector
[EditingComponentProperty(nameof(MediaFilesSelectorProperties.LibraryName), "Graphics")]
// Limits the maximum number of files that can be selected at once
[EditingComponentProperty(nameof(MediaFilesSelectorProperties.MaxFilesLimit), 5)]
// Configures the allowed file extensions for the selected files
[EditingComponentProperty(nameof(MediaFilesSelectorProperties.AllowedExtensions), ".gif;.png;.jpg;.jpeg")]
// Returns a list of media files selector items (objects that contain the GUIDs of selected media files)
public IList<MediaFilesSelectorItem> Images { get; set; }



Component's controller class



// Retrieves the GUID of the first selected media file from the 'Images' property
Guid guid = GetProperties().Images?.FirstOrDefault()?.FileGuid ?? Guid.Empty;
// Retrieves the MediaFileInfo object that corresponds to the selected media file GUID
MediaFileInfo mediaFile = MediaFileInfoProvider.GetMediaFileInfo(guid, SiteContext.CurrentSiteName);

string url = String.Empty;
if (mediaFile != null)
{
    // Retrieves an URL of the selected media file
    url = MediaLibraryHelper.GetDirectUrl(mediaFile);
}


Configuring maximum file upload size and timeout

The media files selector also provides a media file uploader for uploading new files into media libraries as part of its functionality. By default, the uploader is limited to 200MB and times out after 120 seconds. If you wish to enable uploads of larger files or you want to set a different timeout interval, edit your MVC project’s web.config file and modify the following values:

  • Modify the value of the <httpRuntime> element’s maxRequestLength and executionTimeout  attributes. Enter the values in kilobytes and seconds.
  • Modify the value of the <requestLimits> element’s maxAllowedContentLength attribute. Enter the value in bytes. The value of the maxAllowedContentLength attribute in kiloBytes must be greater or equal to the value of the maxRequestLengthattribute.



<!-- Scopes the maximum file size configuration to only affect files uploaded using the media files selector -->
<location path="Kentico.Uploaders">
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="MAXSIZE_IN_BYTES" />
      </requestFiltering>
    </security>
  </system.webServer>
  <system.web>
    <httpRuntime maxRequestLength="MAXSIZE_IN_KILOBYTES" executionTimeout="NUMBER_IN_SECONDS" />
  </system.web>
</location> 


Page selector

The page selector form component allows users to select pages from the content tree using a dialog window. The selector returns a collection of PageSelectorItem objects, which contain the NodeGUID property with a GUID of the selected page. If you wish to obtain a page’s node alias path, use the path selector component instead.

Note: In Kentico 12 Service Pack , the page selector can only be used to select a single page – the returned collection of PageSelectorItem objects always contains only one object. Due to forward compatibility and to limit any possible future changes in your project, the return type is a collection.

Page selector interface

The page selector form component has the following configurable properties:

Property

Type

Description

RootPath

string

Limits the selection of pages to a subtree rooted at a page identified by its node alias path (e.g. “/Products/Coffee-grinders”). Only the specified page and its sub-pages can be selected. If not configured, users can select from the entire content tree.

The following example shows the declaration of a property in a page builder component’s property model class that has the PageSelector form component assigned as its editing component. The selected page is then retrieved in the corresponding component’s controller.

Component's model class



// Assigns a selector component to the Pages property
[EditingComponent(PageSelector.IDENTIFIER)]
// Limits the selection of pages to a subtree rooted at the 'Products' page
[EditingComponentProperty(nameof(PageSelectorProperties.RootPath), "/Products")]
// Returns a list of page selector items (node GUIDs)
public IList<PageSelectorItem> Pages { get; set; }



Component's controller class



// Retrieves the node GUID of the selected page from the 'Pages' property
Guid? selectedPageGuid = GetProperties().Pages?.FirstOrDefault()?.NodeGuid;
// Retrieves the page that corresponds to the selected GUID
TreeNode page = DocumentHelper.GetDocuments()
                .WhereEquals("NodeGUID", selectedPageGuid)
                .Culture("en-us")
                .TopN(1)
                .FirstOrDefault();


Path selector

The path selector form component allows users to select pages from the content tree using a dialog window. The path selector returns a collection of PathSelectorItem objects, which contain the NodeAliasPath property with a node alias path of the selected page. If you wish to obtain a page’s GUID, use the page selector component instead.

Note: In Kentico 12 Service Pack , the path selector can only be used to select a single page – the returned collection of PathSelectorItem objects always contains only one object. Due to forward compatibility and to limit any possible future changes in your project, the return type is a collection.

Path selector interface

The path selector form component has the following configurable properties:

Property

Type

Description

RootPath

string

Limits the selection of pages to a subtree rooted at a page identified by its node alias path (e.g. “/Products/Coffee-grinders”). Only the specified page and its sub-pages can be selected. If not configured, users can select from the entire content tree.

The following example shows the declaration of a property in a page builder component’s model class that has the PathSelectorform component assigned as its editing component. The selected page is then retrieved in the corresponding component’s controller.

Component's model class



// Assigns a selector component to the 'PagePaths' property
[EditingComponent(PathSelector.IDENTIFIER)]
// Limits the selection of pages to a subtree rooted at the 'Products' page
[EditingComponentProperty(nameof(PathSelectorProperties.RootPath), "/Products")]
// Returns a list of path selector items (page paths)
public IList<PathSelectorItem> PagePaths { get; set; }


Component's controller class



// Retrieves the node alias path of the selected page from the 'PagePaths' property
string selectedPagePath = GetProperties().PagePaths?.FirstOrDefault()?.NodeAliasPath;
// Retrieves the page that corresponds to the selected node alias path
TreeNode page = DocumentHelper.GetDocuments()
                .Path(selectedPagePath)
                .OnCurrentSite()
                .TopN(1)
                .FirstOrDefault();


JavaScript APIs for creating custom selectors

The JavaScript API provides an alternative way to integrate the page, path and media files selector functionality into custom code. For example, this API can be used to invoke selector dialogs directly from within a widget’s inline editor.

Media files selector JavaScript API

To open the media files selector (its modal dialog), use the window.kentico.modalDialog.mediaFilesSelector.open(options) function. To call this function, make sure you have the page builder scripts loaded in your view. Provide an options object with the following properties as a parameter of the function:

Required properties

Property

Description

applyCallback

A callback function invoked when the media file selector’s confirmation button is clicked. The parameter of the callback function contains an array of media file objects. Within this function, you need to ensure displaying of the selected files using the properties available in the media file object and ensure the propagation of the media files selected in the selector to the widget or form component which opened the selector.

To propagate the selected files from the selector to the component which invoked the selector:

  • use the updateProperty custom event if the selector was opened from a widget through an inline editor.
  • modify the value of the input element if the selector was opened from a form component.

Optional properties

Property

Description

libraryName

A string code name of a (single) media library from which you can select files in the selector. If not specified, the selector allows selecting from all media libraries of the current site for which the user has permissions.

maxFilesLimit

A number property stating the limit on the maximum number of files allowed to be selected. 1 stands for a single file selection and 0 stands for unlimited file selection. If not specified, the selector is configured for a single file selection by default.

selectedValues

An array of objects with the fileGuid property that represent initially selected media files (their GUIDs).

  • i.e. [{ fileGuid: “c3793d7a-cc6e-44b2-ab82-cbe8e2a12345” }]

allowedExtensions

A semicolon-delimited string of file extensions that specify the allowed file extensions for the files to be selected. The listed extensions need to form a subset of allowed extensions specified in the Media file allowed extensions site settings key. When no allowed extensions are specified, all files with the extensions from the site settings key can be selected.

The media file object represents a selected file from a media library. Following is a list of properties available for each media file object – the main purpose of these properties is displaying the selected files and information about them. If you need to persistently store the selected files for later use, storing only the fileGuidproperty should be sufficient.

Media file object properties

Property

Description

name

A string property representing the name of the file.

extension

A string property representing the file type extension.

fileGuid

A string property representing the GUID of the selected file.

url

A string property representing the relative URL from which you can access the selected file.

thumbnailUrls

A property representing the URLs of the image file’s thumbnails. Not all file types support thumbnails (e.g. .pdf files). The property consists of three string URLs, each for a different typified size of the thumbnail: small, medium, and large.

mimeType

A string property representing the MIME type of the file.

size

A number property representing the size of the file in bytes.

title

A string property representing the title of the selected file.

description

A string property representing the description of the file.

folderPath

A string property representing the relative path to the folder within the media library containing the selected file.

libraryName

A string property representing the name of the library from which the file was selected.

siteName

A string property representing the name of the site to which the file (i.e. the media library) belongs.

isValid

A boolean value indicating whether the selected file is valid (e.g. if the file was not deleted from the media library after being selected). If false, the object’s other properties might not be correctly set.

Apart from the properties listed above, the media file selector modal dialog shares the following properties with the general Kentico modal dialog from which it is derived: title, theme, width, maximized, applyButtonText, cancelButtonText, cancelCallback

The following example showcases a script of an  inline editor  that opens a media file selector. The inline editor’s value in this example is a string property containing a GUID which identifies the selected media file.

Example - Opening the media file selector in an inline editor using the API



(function () {
// Registers the 'image-selector' inline editor within the page builder scripts
window.kentico.pageBuilder.registerInlineEditor("image-selector", {
    init: function (options) {
        var editor = options.editor;
        var button = editor.querySelector("button");

        button.addEventListener("click", function () {
            // Sets the options object with individual properties
            var dialogOptions = {
                libraryName: "Graphics",
                maxFilesLimit: 1,
                allowedExtensions: ".gif;.png;.jpg;.jpeg",
                selectedValues: options.propertyValue,

                // Defines the applyCallback function invoked on click of the selector's confirmation button
                applyCallback: function (files) {
                    var newFile = files[0];

                    // Checks if the image isn't already selected
                    if (options.propertyValue && newFile.fileGuid === options.propertyValue[0].fileGuid) {
                        return {
                            closeDialog: true
                        };
                    }

                    // Creates a custom event that notifies the widget about a change in the value of a property
                    var event = new CustomEvent("updateProperty", {
                            detail: {
                                value: [{ fileGuid: newFile.fileGuid }],
                                name: options.propertyName
                            }
                        });

                    editor.dispatchEvent(event);

                    return {
                        closeDialog: true
                    };
                }
            };

            // Opens the selector modal dialog 
            window.kentico.modalDialog.mediaFilesSelector.open(dialogOptions);
        });
    }
  });
})();


Page selector JavaScript API

The page and path selector form components differ only in the type of the returned data. Due to their similarity, they share the same JavaScipt API that can be configured to return either a page’s NodeGUID or NodeAliasPath. To open the page selector, use the window.kentico.modalDialog.pageSelector.open(options) function included as part of the page builder scripts bundle. Provide an options object with the following properties as a parameter of the function:

Required properties

Property

Description

applyCallback

A callback function invoked when the selector’s confirmation button is clicked. Within this function, you need to ensure the propagation of the pages selected in the selector to the widget or form component which opened the selector.

To retrieve the selected pages, access the object passed as the parameter of the applyCallback function, which contains an array of selected page objects. Each of these selected page objects has the following properties:

  • nodeId – the ID of the selected node in the database.
  • nodeGuid – the GUID of the selected node in the database.
  • nodeAliasPath – the node alias path of the page.
  • namePath – the name path of the page.
  • name – the title of the page, as displayed in the content tree.
  • url – the relative preview URL of the selected page.
  • icon – the icon class used with the page in the UI.
  • isValid – a boolean property, which indicates whether the page is a valid page to be selected in the dialog (user has permissions to view the page, the page has not been deleted while the dialog was opened, etc.).

Note: In Kentico 12 Service Pack, the page selector can only be used to select a single page – the returned array of selected pages always contains only one object. Due to forward compatibility and to limit any possible future changes in your project, the return type is an array.

To propagate the selected pages from the selector to the component which invoked the selector:

  • use the updateProperty custom event if the selector was opened from a widget through an inline editor.
  • modify the value of the input element if the selector was opened from a form component.

Optional properties

Property

Description

rootPath

A string property that limits the selection of pages to a subtree with root specified by its node alias path (e.g. “/Products/Coffee-grinders”). Only the specified page and its sub-pages can be selected. If not specified, the whole content tree is allowed.

identifierMode

A property that specifies the identifier format used by the selectedValues property. Possible values are:

  • path – identification by node alias paths.
  • guid – identification by node GUIDs.

selectedValues

Note: If you use the selectedValues property, you are required to specify the identifierMode property.

A property that defines the set of pages that are pre-selected when the dialog is opened. selectedValues is an array of objects that each contain an identifier property. This property must contain either node alias paths or GUIDs of desired pages, depending on the configuration of the identifierMode property. When selected values are not specified, no pages are pre-selected.

Using GUIDs as identifiers



kentico.modalDialog.pageSelector.open({
    ...

    identifierMode: "guid",
    selectedValues: [{identifier: "c3793d7a-cc6e-44b2-ab82-cbe8e2a12345"}]
});


Using node alias paths as identifiers



kentico.modalDialog.pageSelector.open({
    ...

    identifierMode: "path",
    selectedValues: [{identifier: "/Products/Coffee-grinders/Tornado-404"}]
});


Apart from the properties listed above, the page selector modal dialog shares the following properties with the general Kentico modal dialog from which it is derived: title, theme, width, maximized, applyButtonText, cancelButtonText, cancelCallback

The following example showcases a script of an inline editor that opens a page selector. The inline editor’s value in this example is a string property containing a GUID which identifies the selected page.

Example - Opening the page selector using the JavaScript API



(function () {
// Registers the 'page-selector' inline editor within the page builder scripts
window.kentico.pageBuilder.registerInlineEditor("page-selector", {
    init: function (options) {
        var editor = options.editor;
        var button = editor.querySelector("button");
        button.addEventListener("click", function () {
            // Sets the options object with individual properties
            var dialogOptions = {
                identifierMode: "guid",
                selectedValues: options.propertyValue ? [{identifier: options.propertyValue[0].nodeGuid}] : [],
                rootPath: "/Products",
                // Defines the applyCallback function invoked on click of the selector's confirmation button
                applyCallback: function (pages) {
                    var selectedPage = pages[0];
                    // Checks if the page isn't already selected
                    if (options.propertyValue && selectedPage.nodeGuid === options.propertyValue[0].nodeGuid) {
                        return {
                            closeDialog: true
                        };
                    }
                    // Creates a custom event that notifies the widget about a change in the value of a property
                    var event = new CustomEvent("updateProperty", {
                            detail: {
                                value: [{nodeGuid: selectedPage.nodeGuid}],
                                name: options.propertyName
                            }
                        });
                    editor.dispatchEvent(event);

                    return {
                            closeDialog: true
                    };
                }
            };
            // Opens the selector modal dialog
            window.kentico.modalDialog.pageSelector.open(dialogOptions);
        });
    }
  });
})();