ZnetDK 4 Mobile

ZnetDK JS API

Client-side Mobile Application JavaScript Methods

The ZnetDK for Mobile framework is invoked through the JavaScript znetdkMobile object.

From a ZnetDK view, call inside a <script> block, the methods you need among those described on this page.

Data list

The basics

The ZnetDK data list is loaded from a remote PHP controller action by page of 20 data rows according to the infinite scrolling pattern.

Add into a ZnetDK view a HTML <ul> element with the id attribute filled in and the data-zdk-load attribute that specifies the remote controller action called to load the data.
The first list item declared (HTML <li> element) is the row template used to display all the items of the data list. Each value to be displayed is surrounded by double braces (i.e. {{myValue}}).
Optionally, the second list item declared is the custom message displayed when no list item exists.
Finally, call the znetdkMobile.list.make() method to initialize and load the data list.

Here is an example of a ZnetDK view with the minimum HTML and JavaScript code required to load list items from the all action of the MyCtrl controller, and then display them.
The number of rows per page is changed to 40 rows (rowsPerPage property is set to 20 by default) to take in account the reduced height of each item element.

EXAMPLE: minimal code for displaying a data list in a view

<ul id="contactlist" class="w3-ul" data-zdk-load="myctrl:all">
    <li>{{label}}</li>
</ul>
<script>
    znetdkMobile.list.rowsPerPage = 40;
    znetdkMobile.list.make('#contactlist');
</script>

And to be complete, you will find below the PHP source code of the MyCtrl controller that provides on demand the item labels to display in the list.

EXAMPLE: PHP controller action that returns a page of items

<?php
namespace app\controller;
class 
MyCtrl extends \AppController {
    static protected function 
action_all() {
        
$maxItems 100// Display of 100 items max.
        
$request = new \Request();
        
$first $request->first// The first item number (zero-based value)
        
$rowCount $request->count// The number of items requested (40 rows in this example)
        
$items = array();
        for (
$index $first$index $first+$rowCount && $index $maxItems$index++) {
            
$items[] = array('label' => "Item $index");
        }
        
$response = new \Response();
        
$response->total $maxItems;
        
$response->rows $items;
        return 
$response// As JSON format
    
}
}
?>

Each call to the myctrl:all PHP controller action to get the items to be displayed in the list is done in AJAX according to the POST method with the paramaters first and count.
The first POST property contains the first item number to display in the list (value 0 when called for the first time) while the count POST property indicates the number of items requested (value 40 in this example).

The znetdkMobile.list properties

 Property rowsPerPage

DESCRIPTION The number of items to request in AJAX from the remote PHP controller action and add to the list when it is displayed for the first time and then when it is scrolled down.
This property can be changed in particular when the height of the first 20 items displayed in the list is lower than the viewport height.
DATATYPE Integer
DEFAULT VALUE 20

EXAMPLE: property rowsPerPage

<script>
    znetdkMobile.list.rowsPerPage = 40;
</script>

 Property heightDiffForNewPage

DESCRIPTION The list height in pixels to scroll down to trigger AJAX loading of a new elements page.
This height can be reduced or increased according to the height of each row displayed in the list.
DATATYPE Integer
DEFAULT VALUE 200

EXAMPLE: property heightDiffForNewPage

<script>
    znetdkMobile.list.heightDiffForNewPage = 300;
</script>

 Property uniqueSearchedKeyword

DESCRIPTION Limit the search in the list to only one keyword when the property is set to true.
By default, multiple keywords can be entered and cumulated to search items in the list.
DATATYPE Boolean
DEFAULT VALUE false

EXAMPLE: property uniqueSearchedKeyword

<script>
    znetdkMobile.list.uniqueSearchedKeyword = true;
</script>

 Property beforeSearchRequestCallback

DESCRIPTION Set a callback function executed just before requesting to the web server, the items to load in the list.
This callback function is particularly useful to change the POST paramaters sent in AJAX to the action of the remote PHP controller.
The requestData parameter passed to the callback function is a simple JavaScript object whose properties and values are the POST parameter names and their associated value as described below:
  • first: property containing the first item number to display in the list (value 0 when called for the first time)
  • count: property that indicates the number of items requested (by default, 20 per page).
  • keyword: property containing the keyword entered by the user in the Searched keyword field.
    This property is an array having multiple keyword values when the list uniqueSearchedKeyword property is set to true.
  • sortfield property specifying the sorting key matching the sort field selected by the user from the Sort result by dropdown.
  • sortorder property indicating the Sort order value (1 for ascending order, -1 for descending order) choosen by the user.
DATATYPE function
DEFAULT VALUE null

EXAMPLE: property beforeSearchRequestCallback

<script>
    /* In this example, the 'search_criteria' POST parameter
     replaces the default 'keyword' parameter. */
    var list = znetdkMobile.list.make('#my-list');
    list.beforeSearchRequestCallback = function(requestData) {
        if (requestData.hasOwnProperty('keyword')) {
            requestData.search_criteria = requestData.keyword[0];
            delete requestData.keyword;
        }
    };
</script>

The znetdkMobile.list methods

 Method make()

DESCRIPTION Instantiate the list object for the specified <ul> HTML element.
PARAMETERS
listElementId String Identifier (id HTML attribute value) of the <ul> HTML element prefixed by a hash symbol (#).
refresh Boolean If set to true or undefined, the refresh action button is displayed for refreshing the list content on demand.
search Boolean If set to true or undefined, the search action button is displayed for filtering/sorting the list content.
RETURNED VALUE Object The instantiated object for the specified list element. This object can then be used to call the setCustomSortCriteria() and setModal() methods.

EXAMPLE: method znetdkMobile.list.make()

<script>
    var list = znetdkMobile.list.make('#my-list', true, false);
</script>

 Method setCustomSortCriteria()

DESCRIPTION Specify the sort criteria that the user can apply to the list when clicking on the search button.
PARAMETERS
sortCriteria Object A JavaScript object whose properties are the sorting keys and values are the sort labels.
defaultSortCriterium String The sorting key to apply by default.
RETURNED VALUE Boolean Value true when succeeded, false if the method is not called into the context of a list object or if its parameter are not properly set.

EXAMPLE: method znetdkMobile.list.setCustomSortCriteria()

<script>
    var list = znetdkMobile.list.make('#my-list');
    list.setCustomSortCriteria({
        id: 'Person # (default)',
        name: 'Name',
        city: 'City',
        country: 'Country'
    }, 'id');
</script>

 Method setModal()

DESCRIPTION Declare the modal dialog to display for editing an existing item or for adding a new one.
PARAMETERS
modalElementId String The identifier of the modal dialog (id HTML attribute).
isFormModifiable Boolean When set to true or undefined, the item can be modified through the modal dialog and the add action bar button is displayed.
onAdd function The function to call back for initialization purpose when adding a new row, just before the modal dialog display.
- The this value allows to access to the modal dialog object.
- The innerForm parameter passed to the callback function is the inner form object.
onEdit function The function to call back for initialization purpose when editing an existing row, just before the modal dialog display.
- The this value allows to access to the modal dialog object.
- The innerForm parameter passed to the callback function is the inner form object.
- The response parameter passed to the callback function is the response object returned by the remote PHP controller action.
RETURNED VALUE Boolean Value true when succeeded, false if the method is not called into the context of a list object.

EXAMPLE: method znetdkMobile.list.setModal()

<script>
    var list = znetdkMobile.list.make('#my-list');
    list.setModal('#my-modal', true, function(innerForm){
        // NEW ITEM
        this.setTitle('New item');
        innerForm.setInputValue('status', 'Draft');
    }, function(innerForm, response) {
        // EDIT ITEM
        this.setTitle('Edit the item');
        innerForm.setInputValue('status', response.status);
    });
</script>

 Method refresh()

DESCRIPTION Refresh the list from the data returned by the remote controller action set for the list through the data-zdk-load HTML5 attribute.
PARAMETERS

no parameter

RETURNED VALUE Boolean Value true when succeeded, false otherwise.

EXAMPLE: method znetdkMobile.list.refresh()

<script>
    var list = znetdkMobile.list.make('#my-list');
    $('#my-button').on('click', function() {
        list.refresh();
    });
</script>

Modal dialog

Displays a modal dialog box suitable for mobile devices with only a few lines of code.

EXAMPLE: view that displays a modal dialog box

<!-- Button to display the modal dialog -->
<button id="my-button" class="w3-button w3-theme-action">Show modal</button>
<!-- The modal dialog definition -->
<div id="my-modal" class="w3-modal">
    <div class="w3-modal-content">
        <div class="w3-container">
            <h4>My modal dialog box</h4>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquet ornare...</p>
            <button type="button" class="cancel w3-button w3-red w3-margin-bottom">Close</button>
        </div>
    </div>
</div>
<!-- The modal is displayed on button click -->
<script>
    $('#my-button').on('click', function(){
        var modalObject = znetdkMobile.modal.make('#my-modal');
        modalObject.open();
    });
</script>

Input form

Connect an HTML input form to the actions of the remote PHP controller to load and submit its data.

The form element is declared with the data-zdk-load HTML5 attribute that specifies the controller action to request in AJAX (i.e. Myctrl::action_detail()) to get the data to load in the input form.
The data-zdk-submit attribute specifies the PHP controller action to execute (i.e. Myctrl::action_submit()) when the submit button is pressed.
The znetdkMobile.form.load() method executed once the view is loaded, sends the AJAX request to the Myctrl::action_detail() PHP controller action.

EXAMPLE: Connecting an input form to controller actions

<!-- Input form definition -->
<form id="my-form" class="w3-container" data-zdk-load="myctrl:detail"
        data-zdk-submit="myctrl:submit">
    <div class="w3-section">
        <label class="zdk-required"><b>Name</b></label>
        <input class="w3-input w3-border w3-margin-bottom" type="text" name="name" required>
        <label><b>City</b></label>
        <input class="w3-input w3-border" type="text" name="city">
        <button class="w3-button w3-block w3-green w3-section w3-padding" type="submit">Submit</button>
    </div>
</form>
<!-- Input form initialization -->
<script>
    var myForm = znetdkMobile.form.make('#my-form');
    myForm.load();
</script>

Below the source code of the MyCtrl PHP controller.
The action_detail() method, executed by the JavaScript znetdkMobile.form.load(), returns the values to display in the input form.
The action_submit() method, triggered on form submit, reads the input form values and shows them throught the information message returned.

EXAMPLE: Input form PHP controller actions

<?php
namespace app\controller;
class 
MyCtrl extends \AppController {
    static protected function 
action_detail() {
        
$response = new \Response();
        
$response->name 'John DOE';
        
$response->city 'Tokyo';
        return 
$response;
    }
    
    static protected function 
action_submit() {
        
$request = new \Request();
        
$response = new \Response();
        
$response->setSuccessMessage('Submit'"Name= {$request->name}, city= {$request->city}");
        return 
$response;
    }
}
?>

Autocomplete

The ZnetDK autocomplete component displays suggestions provided by a remote PHP controller action while the user enters text.

First, add into a ZnetDK view a HTML <input> element with the id attribute filled in and the type attribute set to search.
Next, call the znetdkMobile.autocomplete.make() method to initialize the autocompletion component.

Below a simple example of view with autocompletion.

EXAMPLE: autocompletion

<input id="my-autocomplete" class="w3-input" type="search">
<script>
    znetdkMobile.autocomplete.make('#my-autocomplete', {
        controller: 'myctrl',
        action: 'suggestions'
    });
</script>

And an example of PHP controller that returns suggestions from the text entered by the user.

EXAMPLE: PHP controller action that provides suggestions

<?php
namespace app\controller;
class 
MyCtrl extends \AppController {
    static protected function 
action_suggestions() {
        
$request = new \Request();
        
$response = new \Response();
        
$suggestions = array();
        
$suggestions[] = array('label' => $request->query 'a');
        
$suggestions[] = array('label' => $request->query 'ab');
        
$suggestions[] = array('label' => $request->query 'abc');
        
$response->setResponse($suggestions);
        return 
$response;
    }
}
?>

Messages

Displays a message to the user by calling a simple method in JavaScript.

Call the znetdkMobile.messages.add() method to display a message for information, for warning or when an error occured.

EXAMPLE: information, warning, error messages

<script>
    znetdkMobile.messages.add('info', 'Information', 'Message for information...');
    znetdkMobile.messages.add('warn', 'Warning', 'Message for warning...');
    znetdkMobile.messages.add('error', 'Error', 'Message when error occured...');
</script>

Call the znetdkMobile.messages.showSnackbar() method to display a transient snackbar message.

EXAMPLE: transient snackbar message

<script>
    znetdkMobile.messages.showSnackbar('Message when success...');
</script>

Call the znetdkMobile.messages.notify() method to display a notification message in a modal dialog box.

EXAMPLE: notification message

<script>
    znetdkMobile.messages.notify('Notification to the user', 'Notification message...', null, function() {
        alert('Click on OK button');
    });
</script>

Call the znetdkMobile.messages.ask() method to display a confirmation message in a modal dialog box.

EXAMPLE: confirmation message

<script>
    znetdkMobile.messages.ask('Asking for the user', 'Do you really want to do it right now?', null, function(isYes) {         var buttonPressed = isYes ? 'YES' : 'NO';
        alert('Click on ' + buttonPressed + ' button');
    });
</script>

AJAX requests

Performs an AJAX request to a remote PHP controller action for getting data or executing a process. This feature is based on the jQuery ajax() method.

Call the znetdkMobile.ajax.request() method with a simple JavaScript object as the parameter to specify the AJAX request options.

Here is an example of AJAX call to the myctrl controller and its sum action, passing the values to be summed as POST parameters and finally specifying a callback function to execute when the request is complete.

EXAMPLE: AJAX request sent to get the sum of two values

<script>
    znetdkMobile.ajax.request({
        controller: 'myctrl',
        action: 'sum',
        data: {value1: 13, value2: 22},
        callback: function (response) {
            znetdkMobile.messages.add('info', 'Result', response.result, false);
        }
    });
</script>

See below the source code of the Myctrl:action_sum() PHP controller action executed in response to this AJAX request.

EXAMPLE: PHP controller action that calculates the sum of two values

<?php
namespace app\controller;
class 
MyCtrl extends \AppController {
    static protected function 
action_sum() {
        
$request = new \Request();
        
$response = new \Response();
        
$response->result $request->value1 $request->value2;
        return 
$response;
    }
}
?>