Widget Developer Documentation

API Reference

All functions and constants are statically defined on the Moboom object. So everything in the API must be prefixed with Moboom::.

API functions are categorized below using tags. Client functions are for working with client devices, URLs, and other metadata; Core functions are those that you will probably use in every widget; CSS/JS functions are those related to styles and scripts; File functions are for files and URLs (client-side or server-side); Image functions are for image-handling; System functions are those that are particularly tied to the Moboom platform or the underlying system; User functions are related to management of the user login table.

~ Placeholder ~

addContent($contentSetId, $params)

$contentSetId
A numeric reference to the content set to be updated.
$params
An associative array of values to be stored in the content set.

This API is used to add a new record to a content set. See Moboom::updateContent() for details. Other than the fact that one API is used to create a record and the other is used to edit a record (and the inclusion of a third parameter), the two APIs are identical.

contentReplace($contentSetId, $contentItemId, $params)

$contentSetId
A numeric reference to the content set to be updated.
$contentItemId
A numeric reference to the item to be updated.
$params
An associative array of values to be stored in the content set.

Identical to Moboom::updateContent() in every way except one: this API is guaranteed to remove the old record before it saves the new fields.

For example, consider a content set that stores addresses. You might have an optional field addressLine2. If you call Moboom::updateContent() when the user edits their address, you may find that the second line cannot easily be removed just by blanking out the text editor in your form. By using Moboom::contentReplace(), you guarantee that there is no leftover data in the record.

There is an important corollary: if you use this API, you must ensure that you include every field in $params, every time you call it. Otherwise you will lose content.

See Moboom::updateContent() for other details and sample code.

createImageUrl( $imageID, $maxWidth=NULL, $maxHeight=NULL)

$imageID
The image ID is returned by Moboom::getWidgetSetting(). You should not pass any other value to this function.
$maxWidth
Optional. If you pass in a numeric value, it will act as the maximum pixel size of the image, and a scaled (not cropped) image will be returned.
$maxHeight
See $maxWidth above.

This function should always be used when displaying images. It not only scales the image, but it ensures that the image is loaded from the CDN, for optimal download speed. See the Images & Files page for more information.

If you do not pass in a specific value for $maxWidth, the system will automatically create a properly-sized image for the client device. In other words, a call to Moboom::getMaxImageWidth() will be applied to the image, ensuring all images are handled adaptively. This is the most common way to use this API.

$img = Moboom::getWidgetSetting( 'featured_image');
$url = Moboom::createImageUrl( $img);
echo "<img src='$url' />";

createUrl( $uri, $params=array())

$uri
The root address of the resource.
$params
Optional. Query params to attach to the URL.

This function must be used to ensure that your URLs are future-proof. What does that mean?

The Moboom platform has some very sophisticated back-end functionality. For example, we have the ability to generate thousands of identical sites from a single template. If you build your widgets without wrapping your URLs in this API, you may end up creating links to the wrong site. 

That’s just one example. While your URLs may work fine now if you simply output them directly, your widget may not be usable on multi-sites, or it may not benefit from future enhancements to the platform.

$url = Moboom::createUrl( 'api-reference', array( 'api' => 'createUrl'));

This API must also be called any time you are using a page setting type.

$page = Moboom::getWidgetSetting('selected_page');
$url  = Moboom::createUrl($page);
echo "<a href='$url'>Click here</a>";

deviceHasProfile( $profile)

$profile
A string which will be matched against the client‘s device.
return
Returns true if the client’s device matches the profile passed in.

This function is used to determine what type of a device a client is using. Because it is available server-side, it allows you to adapt your content intelligently to the features of the client device. 

Following is a complete list of profiles which are supported by this API:

            Desktop | Mobile | Tablet | Feature Phone | Smartphone | iPhone | iPad |
            iPod | iOS | Android | Android 2.3 | BlackBerry | Windows Phone

getBaseUrl()

This function returns the path to the folder in which your widget’s assets reside. You must use it any time you are loading a client-side asset such as a JavaScript file, CSS file, or image resource stored in your widget. It is not needed for any resource which is stored outside your widget (such as in the Library or in a third-party CDN).

Moboom::registerScriptFile( Moboom::getBaseUrl() . 'scripts.js', Moboom::POS_END);

getContext()

This function returns an array of attributes which describe the context of the current search query.

$context = Moboom::getContext();
$startAt  = $context['from'];   // the first result returned in this page
$pageSize = $context['size'];   // number of elements returned in each page
$total    = $context['total'];  // complete size of search-results set

The ['from'] element of the returned array tells you the numeric index of the first entry in the data set your widget has been given. The ['size'] element tells you the page size, which will of course be greater than or equal to the number of elements in the array returned by Moboom::getWidgetSetting() on the relevant user setting. The ['total'] element is the complete size of the data set, including all pages.

See the documentation on Collections & Content Sets, especially the section on paging, for more details and sample code.

getGoogleAnalyticsCode()

Returns the Google Analytics tracking identifier, as set in the Site Settings page.

Note that when you enter a tracking ID in Site Settings, Moboom will automatically create the tracking codes for you (on your live site, not your preview site). So you should rarely need to use this API.

getInstanceId()

Returns a unique identifier for an instance of a widget. If more than one instance of a widget is included on a page, the instance identifiers will be unique.

One situation in which you might find this useful is connecting specific items to your JavaScript. For example, when building a widget that creates a tabbed interface (like on the Samples page) or an accordion, you may need to tie each trigger link to a specific <div> to display. You can use this API to ensure that those objects are properly linked.

// the next line uses the API to generate a truly unique
// ID for this widget instance, to differentiate it from
// other instances on this page. the generated ID is
// quite long (36 characters)
//
$trulyUniqueID = Moboom::getInstanceId();

// this alternative uses a 4-digit random number to
// act as a unique ID
//
$sortOfUniqueID = mt_rand( 1000, 9999);

// use to connect a specific DOM element to your JavaScript
//
echo "<div id='myWidget$trulyUniqueId'>'";

getMaxImageWidth()

Returns the maximum width that a client device can support. See the Images & Files page for details and sample code.

Note that Moboom::createImageUrl() automatically applies image-sizing for you. Moboom::getMaxImageWidth() is provided for your convenience.

getPageSlug()

Returns the slug of the current page. For example, on the page you’re currently viewing, this function would return “api-reference”.

getPageTitle()

Returns the title of the current page. For example, on the page you’re currently viewing, this function would return “API Reference”. Note that it does not include the prefix (set on the Site Settings page).

getParam( $param)

$param
The name of the parameter to retrieve.

Retrieves a parameter from one of the following collections: $_COOKIE, $_POST, and $_GET, in that order. In its simplest use case, it is a shorthand for retrieving query variables from the URL.

$itemID = Moboom::getParam( 'itemID');

getRequestUrl()

Returns the fully-specified path of the current page. 

getSiteName()

Returns the name of the site. This is set in the Site Settings page.

getUsername()

Returns the name of the user logged in (via Moboom::userLogin()). If no user is logged in, this API returns false. This is the correct way to determine if a user is currently logged in.

getWidgetSetting( $name, $default=NULL)

$name
The parameter name, as entered in the widget settings pane in the widget editor.
$default
Optional. If the parameter was not entered by the user, this value will be used instead.
return
Returns the setting, as entered by the user. Some data types return keyed arrays (e.g., the link type), some return strings (the text type), and some return IDs or codes (the image type).

This method links the user settings with your widget code.

includePageElement( $pageElement, $context)

$pageElement
The ID of the page element to display.
$context
Required. Takes a string describing the context that should be passed to the page element. See below for details.

This function renders a page element inside your widget. The page element must be selected in a user setting.

The $context parameter is a query-param-style string. The variables which you can use are described on the Collections & Content Sets page, in the section on data-paging. You can pass an empty string if no context-override is needed.

$pageElt = Moboom::getWidgetSetting( 'pe');
$context = "size=1000";
Moboom::includePageElement( $pageElt, $context);

includeWidget( $name, $settings, $cssId=NULL, $cssClass=NULL)

$name
The name of the widget.
$settings
An array of values that will be passed to the widget. The widget will be able to use these values in the same way as if the user had entered them manually in the settings panel.
$cssId
Optional. Applies an ID attribute to the widget container.
$cssClass
Optional. Applies a CSS class to the widget container.

Renders a widget inside your widget. This function takes the widget name, which is not guaranteed to be globally unique. If you are loading a custom widget whose name you know is globally unique, then this function should be fine. Otherwise, you should use Moboom::includeWidgetByExtensionId(). See that function below for more information and sample code.

includeWidgetByExtensionId( $widgetId, $settings, $cssId=NULL, $cssClass=NULL)

$widgetId
The globally-unique identifier for the widget. See below for comments.
$settings
An array of values that will be passed to the widget. The widget will be able to use these values in the same way as if the user had entered them manually in the settings panel.
$cssId
Optional. Applies an ID attribute to the widget container.
$cssClass
Optional. Applies a CSS class to the widget container.

Renders a widget inside your widget. This function takes the widget ID, which is a globally-unique identifier. To get the widget ID, go to your Library page and find the widget. Click the widget icon; in the popup window that shows the widget information you’ll find the widget ID. It will be in a form similar to this: 12345678-abcd-1234-5678-123456789abc. If the widget is in your library, then you can render it using this method — that includes widgets that you didn’t write yourself.

$widgetName = 'Heading';
$settings = array('text' => 'My Heading', 'level' => '2');
Moboom::includeWidget($widgetName, $settings, 'pageHeader');

$widgetId = '12345678-abcd-1234-5678-123456789abc';
$settings = array('username' => 'John Doe', 'title' => 'Mr.');
Moboom::includeWidgetByExtensionId($widgetId, $settings, 'testID', 'testClass');

If your widget uses a collection for one of its settings, the $settings parameter will be an array of arrays.

$widgetId = '7b75c811-e347-0cc5-5ca9-537befbc009e';
$settings = array(
    'list' => [
        [
            'text' => 'Page Element #1',
            'page_element' => '779305da-6a15-42c6-05eb-541b3793c2d2'
        ],
        [
            'text' => 'Page Element #2',
            'page_element' => '6a1505da-7793-93c2-533a-541b37d242c6'
        ]
    ]
);
Moboom::includeWidgetByExtensionId( $widgetId, $settings);
Note
This is not a source-code include. You cannot use this method to keep a library of utility functions inside a widget, then include those functions in other widgets. These APIs only include the rendered output of a widget.

isDesignMode()

Returns true only when your site is being viewed in the Moboom studio.

isLive()

Returns true only when your site is being viewed using its published URL.

isPreviewMode()

Returns true only when your site is being viewed in preview mode, using a URL like “http://yousite.preview.moboom.com/”.

registerCss ( $id, $css)

$id
Each snippet of CSS needs its own identifier. Pass any unique string on this parameter.
$css
The style declarations to be included.

Use this function to install styles directly into the document header. The style rules you provide will be wrapped in <style> tags.

$css = 'body { color: blue }';
Moboom::registerCss( 'bodyColors', $css);

registerCssFile( $url, $media=NULL)

$url
The path to the CSS file.
$media
Optional. The device type for inclusion on the generated link tag.

Use this function to generate a link to an external CSS file. For CSS file assets that are stored in your widget, be sure to use Moboom::getBaseUrl() to generate the correct reference to the file.

$colorsCSS = '//cdnjs.cloudflare.com/ajax/libs/colors/1.0/colors.min.css';
Moboom::registerCssFile( $colorsCSS);

$localCSS = 'myWidgetStyles.css';
Moboom::registerCssFile( Moboom::getBaseUrl() . $localCSS);

registerScript( $id, $script, $position=Moboom::POS_HEAD)

$id
Each snippet of JavaScript needs its own identifier. Pass any unique string on this parameter.
$script
The JavaScript code to be included.
$position
Optional. Where in the HTML document the script should be placed.

This function loads a snippet of JavaScript code directly into the document. It differs from Moboom::registerScriptFile() in two important ways:

  • Moboom::registerScript() loads script commands directly, while Moboom::registerScriptFile() loads a JavaScript file. If you need to build a script dynamically, you should use Moboom::registerScript().
  • Scripts installed with Moboom::registerScriptFile() are duplicate-protected. In other words, multiple instances of the same widget type will not generate multiple instances of the <script> tag. In contrast, scripts installed with Moboom::registerScript() will be installed once for every instance of the widget.

Valid values for the optional $position parameter:

  • Moboom::POS_HEAD — The script is placed in the <head> section of the document
  • Moboom::POS_BEGIN — The script is placed at the beginning of the <body> section
  • Moboom::POS_END — The script is placed at the end of the <body> section (this is the best practice, in general)
  • Moboom::POS_LOAD — The script is called from a window.onload function
  • Moboom::POS_READY — The script is placed inside a jQuery document-ready function
// pass a value from the user settings into a javascript snippet
//
$size = Moboom::getWidgetSetting( 'size', 'large');
$script = "shirtSize = $size";
Moboom::registerScript( 'sizeScript', $script, Moboom::POS_HEAD);

registerScriptFile( $url, $position=Moboom::POS_HEAD)

$url
The path to the script file.
$position
Optional. Where in the HTML document the script should be placed.

This function installs a JavaScript file in your document.

See the comments on Moboom::registerScript() for a discussion of the $position parameter.

$scriptURL = '//cdnjs.cloudflare.com/ajax/libs/easy-pie-chart/2.1.4/jquery.easypiechart.min.js';
Moboom::registerScriptFile( $scriptURL, Moboom::POS_END);

$scriptURL = Moboom::getBaseUrl() . 'myWidgetScripts.js';
Moboom::registerScriptFile( $scriptURL, Moboom::POS_END);

sendEmail( $message, $subject, $recipient)

$message
The body of the email message.
$subject
The subject line of your email.
$recipient
The recipient of your email. Accepts only one address at a time.

Sends a single email.

setCookie( $name, $value, $atts=NULL)

$name
The name of the cookie.
$value
The new value for the cookie.
$atts
Optional. Attributes for the cookie. See below for details.

Creates, modifies, or deletes a cookie. Unless you indicate otherwise in $atts, all cookies created with this API will expire at the end of the user’s session. In addition, all cookies are scoped within your widget, rather than within your application. To communicate between widgets, use the Moboom::setSession() API.

The following values can be set in the $atts parameter:

  • expires — accepts a UNIX timestamp to indicate how long the cookie should remain valid.
  • path — an optional subdirectory which limits the scope of the cookie.
  • domain — the domain or subdomain in which the cookie is valid.
  • maxAge — the number of seconds that the cookie should remain valid.
// sets a basic session-length cookie
//
$name = 'username';
$value = 'Elizabeth';
Moboom::setCookie( $name, $value);

// sets a cookie which persists for 2 weeks
//
$atts = array( 'expires' => time() + 60*60*24*14 );
Moboom::setCookie( $name, $value, $atts);

// this does the same thing
//
$atts = array( 'maxAge' => 60*60*24*14 );
Moboom::setCookie( $name, $value, $atts);

// deletes a cookie, by giving it an expiration in the past
//
$atts = array( 'expires' => time() - 1000);
Moboom::setCookie( $name, $value, $atts);
Note that there is no corresponding getCookie() method. You can access cookies directly using the $_COOKIE collection. Keep in mind that this collection is read-only; if you need to write cookies, you must use the API.

updateContent( $contentSetId, $contentItemId, $params)

$contentSetId
A numeric reference to the content set to be updated.
$contentItemId
A numeric reference to the item to be updated. If you’re adding a new content item, use NULL.
$params
An associative array of values to be stored in the content set.

This API allows you to update a record in a content set. The $contentSetId parameter is retrieved by creating a widget setting with the Content Select data type. This allows the user to select the proper content set.

The $contentItemId parameter must be passed in from a content-aware bubble that uses the _id field from the content set. This is an internally-managed identifier assigned to each record in your content set.

The $params parameter is a set of key-value pairs. The keys should match field names in your content set.

Typically, this API is used on the back end of a form processor. So you might build a widget that presents a form with pre-existing data loaded from a content set; when the form is submitted, the new data is written to the content set.

Note
You can use this API to add fields to your content set that didn’t already exist. This gives you great flexibility, but use with caution!

Data is written asynchronously. The update request is initiated after your widget is completely rendered. Therefore:

  • You will not see new data in the current instance of the widget. Any requests to Moboom::getWidgetSetting() will have old data, even if you call that API after Moboom::updateContent().
  • Even if you call Moboom::redirectTo( Moboom::getRequestUrl() ), which forces a page refresh, you are not guaranteed to see the new data. The asynchronous update job may not have finished by the time your widget renders. A typical timeframe for the operation to complete is 3–5 seconds.

For now, the best practice is to insert an intermediate page (“thank you for your submission”) before you attempt to load the new data from the content set.

// retrieve the user settings. see the sample at right
//
$contentSetId = Moboom::getWidgetSetting( 'cs');
$userId       = Moboom::getWidgetSetting( 'id');

if ( !empty( $_POST['submit'])) {

    // create an array of values to store. the keys
    // match the field names in the content set. the
    // field values would probably be retrieved
    // from $_POST
    //
    // note the last entry in the array; this is how
    // to write to data structures within your content 
    // set
    //
    $fields = array(
        'username'  => "new username",
        'email'     => "new email address",
        'addresses' =>
            array( "address" =>
                    array( "city" => "new city"))
    );

    Moboom::updateContent( $contentSetId, $userId, $fields );
}
else {
    // load the other settings from the widget. these settings
    // are not needed for handling the form post; they are only
    // for pre-filling the form
    //
    $username     = Moboom::getWidgetSetting( 'username');
    $email        = Moboom::getWidgetSetting( 'email');

    echo '<form action="post">';
    // etc
}
Related APIs
Be sure to check out Moboom::addContent() and Moboom::contentReplace(). All three of these APIs are important tools when working with content sets.

userChangePassword( $oldPW, $newPW, $successURL, $failureURL=NULL)

$oldPW
The user’s existing password.
$newPW
The preferred new password.
$successURL
The web page to redirect to after the password is updated.
$failureURL
Optional. If there is a problem, redirect here. If the parameter is omitted, $successURL will be used regardless of outcome.

This API changes the password associated with the user who is currently logged in. 

userGet()

Returns an associative array of all custom properties associated with the currently logged-in user. See the User Management page for more details.

userGetProperty( $propertyName, $defaultValue=false)

$propertyName
Which property to retrieve from the user table.
$defaultValue
Optional. If $propertyName has no value in the user table, this value is returned in its place.
return
Returns the value of the specified entry in the user table.

Returns a single (scalar) value from the user table for the current user. To retrieve all values simultaneously, use Moboom::userGet(). See User Management for more details and sample code.

userLogin( $username, $password, $successURL, $failureURL=NULL)

$username
The name of the user to log in. This name must match a username that was created with Moboom::userRegister().
$password
The user’s password.
$successURL
The web page to redirect to after a successful authentication.
$failureURL
Optional. The web page to redirect to if authentication fails. If the parameter is omitted, $successURL will be used regardless of outcome.

This API processes a user login action. The username and password will most likely be entered in a form. See User Management for more details and sample code.

userLogout( $redirectURL)

$redirectURL
The web page to redirect to after the user has been logged out.

Ends a user’s session and redirects them to a new page.

userRegister( $username, $password, $properties, $successUrl, $failureUrl=NULL)

$username
The name of the user account to create in the user table.
$password
The initial password to associate with the new user.
$properties
An associative array of properties to attach to the user record. As this parameter is required, you should pass in an empty array if you don’t need to store properties.
$successURL
The web page to redirect to after a successful registration.
$failureURL
Optional. The web page to redirect to if registration fails. If the parameter is omitted, $successURL will be used regardless of outcome.

Adds a new user. Minimal validation is performed inside this API. It will of course check for empty or duplicate usernames, but it does not ensure that the password is strong (or even non-empty).

You can add custom name–value pairs to a user at registration time by passing in an associative array in the $properties parameter. Properties can be added or modified later using Moboom::userSetProperty() or Moboom::userSet().

See User Management for more details and sample code

userSet( $properties)

$properties
An associative array of properties to attach to the user record.

Attaches one or more properties to the record of the currently logged-in user. This method does a deep data-merge, so you can pass in a nested array of values.

$properties = array(
    'version'   => '1.0',
    'lastLogin' => array(
        'when'    => time(),
        'where'   => $_SERVER['REMOTE_ADDR']
    )
);
Moboom::userSet( $properties);

userSetProperty( $propertyName, $value)

$propertyName
Which property to set in the user table.
$value
The new value of the property.

Sets a single property for the currently logged-in user. The $value may be a scalar or an associative array.