abdus

How to build a simple dashboard with AJAX functionality using a Process module

Recommended Posts

After this tutorial you'll have learned how to:

  • Build a Process module
  • Make an AJAX request to backend
  • Serve JSON as response

Let's say you want to display the latest orders in a dashboard that you can access from admin panel. And you want it to refresh its content with a button click. Most straightforward and proper way (that I know of) is to create a Process module, as they're built for this purpose.

First, create a directory under /site/modules/, call it ProcessDashboard, and create a file named ProcessDashboard.module under that directory. Following is about the least amount of code you need to create a Process module.

<?php namespace ProcessWire;


class ProcessDashboard extends Process
{
    public static function getModuleInfo() {
        return [
            'title' => 'Orders Dashboard',
            'summary' => 'Shows latest orders',
            'version' => '0.0.1',
            'author' => 'abdus',
            'autoload' => true,
            
            // to automatically create process page
            'page' => [
                'name' => 'order-dashboard',
                'title' => 'Orders',
                'template' => 'admin'
            ]
        ];
    }

    public function ___execute()
    {
        return 'hello';
    }
}

Once you refresh module cache from Modules > Refresh, you'll see your module. Install it.

chrome_2017-04-29_17-03-07.thumb.png.cf2bad54019bcc4eb354168dc5df14fb.png

It will create an admin page under admin (/processwire/) and will show up as a new item in top menu, and when you click on it, it will show the markup we've built in execute() function.

chrome_2017-04-29_17-12-11.thumb.png.72112716449f08dfc872dee86a5e030a.png

 

All right, now let's make it do something useful. Let's add create a data list to display latest orders. We'll change execute() function to render a data table.

public function ___execute()
{
    /* @var $table MarkupAdminDataTable  */
    $table = $this->modules->MarkupAdminDataTable;
    $table->setID($this->className . 'Table'); // "#ProcessDashboardTable"
    $table->headerRow([
        'Product',
        'Date',
        'Total'
    ]);


    // fill the table
    foreach ($this->getLatest(10) as $order) {
        $table->row([
            $order['title'],
            $order['date'],
            $order['total']
        ]);
    }


    // to refresh items
    $refreshButton = $this->modules->InputfieldSubmit;
    $refreshButton->name = 'refresh';
    $refreshButton->id = $this->className . 'Refresh'; // "#ProcessDashboardRefresh"
    $refreshButton->value = 'Refresh'; // label of the button
    
    return $table->render() . $refreshButton->render();
}

where getLatest() function finds and returns the latest orders (with only title, date and total fields)

protected function getLatest($limit = 5, $start = 0) {
    // find last $limit orders, starting from $start
    $orders = $this->pages->find("template=order, sort=-created, limit=$limit, start=$start");

    // Only return what's necessary
    return $orders->explode(function ($order) {
        return [
            'title' => $order->title,
            'date' => date('Y-m-d h:i:s', $order->created),
            'total' => $order->total
        ];
    });
}

When you refresh the page, you should see a table like this

chrome_2017-04-29_18-32-47.thumb.png.7c915544b190bb099d3086e0a66f3e76.png
Now we'll make that Refresh button work. When the button is clicked, it will make an AJAX request to ./latest endpoint, which will return a JSON of latest orders. We need some JS to make AJAX request and render new values. Create a JS file ./assets/dashboard.js inside the module directory.

window.addEventListener('DOMContentLoaded', function () {

    let refresh = document.querySelector('#ProcessDashboardRefresh');
    let table = document.querySelector('#ProcessDashboardTable');

    refresh.addEventListener('click', function (e) {
        // https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
        e.preventDefault();
      
        // Send a GET request to ./latest
        // http://api.jquery.com/jquery.getjson/
        $.getJSON('./latest', {
            limit: 10
        }, function (data) {
            // check if data is how we want it
            // if (data.length) {}  etc

            // it's good to go, update the table
            updateTable(data);
        });
    });

    function renderRow(row) {
        return `<tr>
                    <td>${row.title}</td>
                    <td>${row.date}</td>
                    <td>${row.total}</td>
                </tr>`;
    }

    function updateTable(rows) {
        table.tBodies[0].innerHTML = rows.map(renderRow).join('');
    }
});

And we'll add this to list of JS that runs on backend inside init() function

public function init()
{
    $scriptUrl = $this->urls->$this . 'assets/dashboard.js';
    $this->config->scripts->add($scriptUrl);
}

Requests to ./latest will be handled by ___executeLatest() function inside the module, just creating the function is enough, PW will do the routing. Here you should notice how we're getting query parameters that are sent with the request.

// handles ./latest endpoint
public function ___executeLatest() {
    // get limit from request, if not provided, default to 10
    $limit = $this->sanitizer->int($this->input->get->limit) ?? 10;
    return json_encode($this->getRandom($limit));
}

Here getRandom() returns random orders to make it look like there's new orders coming in. 

protected function getRandom($limit = 5)
{
    $orders = $this->pages->find("template=order, sort=random, limit=$limit");
    return $orders->explode(function ($order) {
        return [
            'title' => $order->title,
            'date' => date('Y-m-d h:i:s', $order->created),
            'total' => $order->total
        ];
    });
}

And we're done. When refresh button is clicked, the table is refreshed with new data.

Here it is in action: 
2017-04-29_19-01-40.mp4 (227KB MP4, 0m4sec)

Here's the source code:
https://gist.github.com/abdusco/2bb649cd2fc181734a132b0e660f64a2

 

[Enhancement] Converting page titles to edit links

If we checkout the source of MarkupAdminDataTable module, we can see we actually have several options on how columns are built.

/**
 * Add a row to the table
 *
 * @param array $a Array of columns that will each be a `<td>`, where each element may be one of the following:
 *   - `string`: converts to `<td>string</td>`
 *   - `array('label' => 'url')`: converts to `<td><a href='url'>label</a></td>`
 *   - `array('label', 'class')`: converts to `<td class='class'>label</td>`
 * @param array $options Optionally specify any one of the following:
 *   - separator (bool): specify true to show a stronger visual separator above the column
 *   - class (string): specify one or more class names to apply to the `<tr>`
 *   - attrs (array): array of attr => value for attributes to add to the `<tr>`
 * @return $this
 *
 */
public function row(array $a, array $options = array()) {}

This means, we can convert a column to link or add CSS classes to it.

// (ProcessDashboard.module, inside ___execute() method)

// fill the table
foreach ($this->getLatest(10) as $order) {
    $table->row([
        $order['title'] => $order['editUrl'], // associative -> becomes link
        $order['date'], // simple -> becomes text
        [$order['total'], 'some-class'] // array -> class is added
    ]);
}

Now, we need to get page edit urls. By changing getLatest() and getRandom() methods to return edit links in addition to previous fields

protected function getLatest($limit = 5, $start = 0)
{
    // find last $limit orders, starting from $offset
    $orders = $this->pages->find("template=order, sort=-created, limit=$limit, start=$start");
    return $orders->explode(function ($order) {
        return [
            'title' => $order->title,
            'date' => date('Y-m-d h:i:s', $order->created),
            'total' => $order->total,
            'editUrl' => $order->editUrl
        ];
    });
}

protected function getRandom($limit = 5)
{
    $orders = $this->pages->find("template=order, sort=random, limit=$limit");
    return $orders->explode(function ($order) {
        return [
            'title' => $order->title,
            'date' => date('Y-m-d h:i:s', $order->created),
            'total' => $order->total,
            'editUrl' => $order->editUrl
        ];
    });
}

and tweaking JS file to render first column as links

function renderRow(row) {
    return `<tr>
                <td><a href="${row.editUrl}">${row.title}</a></td>
                <td>${row.date}</td>
                <td>${row.total}</td>
            </tr>`;
}

we get a much more practical dashboard.

2017-04-30_15-34-09.thumb.gif.e050cb9396156b792244e8dfa7f9a704.gif

 

  • Like 25

Share this post


Link to post
Share on other sites

Thanks @abdus for this useful tutorial! If you could also add how to turn the values of the first column into links, then it would be a 100% perfect example.

  • Like 1

Share this post


Link to post
Share on other sites
1 hour ago, szabesz said:

Thanks @abdus for this useful tutorial! If you could also add how to turn the values of the first column into links, then it would be a 100% perfect example.

Thanks for the suggestion, I've added it to the original post.

  • Like 4

Share this post


Link to post
Share on other sites

hi abdus,

thanks for your effort on helping others :) maybe i can suggest you to take a tool that lots of people are using here for creating micro-screencasts as animated gifs: http://www.cockos.com/licecap/

licecap_rules.gif

very easy, very helpful :)

  • Like 3

Share this post


Link to post
Share on other sites

I've been using ShareX for the screencasts, but it can't handle high DPI screens very well (might be ffmpeg's fault, though), and cursor is offset a bit.
Just tried LICEcap, it seems to work on high DPI screen just fine. I'll use this one from now on.

Thank you very much for the suggestion @bernhard!

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By FrancisChung
      Hi,
      I was wondering if anyone knew what this did? 

      If so, do you know what modules it actually impacts? Is there another log that lists the action it took?

      I'm having some weird problems with PHP duplicate declaration per link below, since this module was run.
       
       
    • By tpr
      AdminOnSteroids
      Various admin tweaks to enhance ProcessWire admin.
      http://modules.processwire.com/modules/admin-on-steroids/
      https://github.com/rolandtoth/AdminOnSteroids

    • By Macrura
      Field Descriptions Extended
      This module enables you to extend field descriptions by dividing short descriptions with a longer text that is revealed in a toggle.
      Github: https://github.com/outflux3/FieldDescriptionsExtended
      Extending your field descriptions using the standard field's description field.
      Once this module is installed, it will automatically search your description field for the presence of 5 dashes (-----).
      Any content above the 5 dashes will be visible and the content below the dashes will be hidden. A 'More...' link will appear at the end of the short description which when clicked will reveal the rest of the description.
      Using Simple Markdown Editor with the description field
      If you have Simple Markdown Editor (InputfieldSimpleMDE) installed, you can enable the field description to have that editor.
      *When using Simple MDE, you can use the button (Insert Horizontal Line) instead of typing 5 dashes. More about SimpleMDE.
      Extending your field descriptions using content from a ProcessWire Page for the field description.
      You may use the content from a ProcessWire page as a field description. This would allow you to easily insert images, links, and use hanna codes.
      To use page content for your field descriptions, please follow these instructions:
      Install Select Fields module (FieldtypeFields) http://modules.processwire.com/modules/fieldtype-fields/ Create a new field using this field type, e.g. field_select. Add the field to any template you will be using for your field descriptions. Setup your help pages (for example under a settings branch) where you will store the field description content,using the template containing the Field Select. Add content to a page and select the field where that content should show. To show a short text before the link to the longer content, separate them with 5 dashes Be sure to update your settings on this page, first enable page content descriptions,then specify the name of the Select Fields field, template to search, and content field. If you create a field description using this method, please note that the description field must be blank for contexts where you want the page content to appear.
      You can freely use template context for field descriptions, but the Page Content method is not context sensitive and will display under all contexts where the description is blank.
      ----
      original post:
      This is a new module, hope to release soon, which allows extended field descriptions, in currently 2 ways.
      The main feature of the module is that you can have a short description and then a 'more...' link which drops down a longer block of text.
      This is achieved by separating the intro/visible text and the rest with 5 dashes.

      Example setup:

      the 2nd way is if you are using AdminThemeUiKit, you can show extended field instructions in a panel. The content of the panel is edited on a regular PW page. This use case would probably not be that common, but if you had a field that required some extended instructions for how to use, this could be useful; Also, since this allows you to target information and instructions down at the field level, it could reduce the amount of documentation needed on a global level, since it is a lot more context targeted.

    • By netcarver
      Part 1 of a 2 part Module & Service Reveal.
      I'm currently working on a new module: ModuleReleaseNotes that was inspired by the work I originally did on making Ryan's ProcessWireUpgrades module "release" aware. In the end, I decided to ditch the approach I was originally taking and instead work on a module that hooked in to the UpgradeConfirmation dialog and the module edit page.
      Aims
      My aims for this module are as follows...
      Make discovery of a module's changes prior to an upgrade a trivial task. Make breaking changes very obvious. Make reading of a module's support documentation post-install a trivial task. Make module authors start to think about how they can improve the change discovery process for their modules. Make sure the display of information from the module support files/commit messages doesn't introduce a vulnerability. Looking at these in turn...
      Making discovery of a module's changes prior to upgrade a trivial task.
      This is done by adding a "What's changed section" to the upgrade confirmation dialog.  This section takes a best-effort approach to showing what's changed between the installed version and the updated version that's available via the module repository.
      At present, it is only able to talk to github-hosted repositories in order to ask them for the release notes, the changelog file (if present) and a list of commits between the git tag that matches the installed version and the tag matching the latest version.
      It will display the Release Notes (if the author is using the feature), else it will display the commits between the tags (if tagging is used by the module author) else it will show the changelog file (if present) else it will show the latest N commits on the master branch (N, of course, being configurable to your liking.)
      An example of the Github Release Notes pulled in for you, taken from Mike Rockett's TextformatterTypographer Module...

      An example of a tag-to-tag commit list from the same module...

      An example of a changelog - formatted to show just the changes (formatting styles will change)...

      Finally, an example of a fallback list of commits - sorry Adrian ...

       
      Making breaking changes obvious.
      This is currently done by searching for a set of configurable search strings. Later versions may be able to support breaking change detection via use of Semantic Versioning - but this may require some way of signalling the use of this versioning standard on a module-by-module basis.
      For now, then, you can customise the default set of change markers. Here I have added my own alias to the list of breaking change markers and the changes section of the changelog is styled accordingly (these will be improved)...

       
      Make reading of a module's support documentation, post-install, a trivial task.
      This is done by making some of the support files (like the README, CHANGELOG and LICENSE files) readable from the module's information/settings screen. There is an option to control the initial open/closed state of this section...

      Here is Tracy's README file from within the module settings page... 

       
      Make module authors start to think about how they can improve the change discovery process for their modules.
      There are notes in each of the sections displayed on the upgrade confirmation page that help authors use each of the features...

       
      Make sure display of external information doesn't introduce a vulnerability.
      This is an ongoing concern, and is the thing that is most likely to delay or prevent this module's release lead to this module's withdrawl should a vulnerability be found. Currently, output is formatted either via Markdown + HTML Purifier (if it was originally a Markdown file) or via htmlspecialchars() if it has come from a plaintext file.
      If you discover a vulnerability, please get in contact with me via the forum PM system.
       
      Ongoing...
      For now, I've concentrated on integration with GitHub, as most people use that platform to host their code. I know a few people are hosting their repositories with BitBucket (PWFoo comes to mind) and some with GitLab (Mike Rockett?) and I would eventually like to have adaptor implementations for these providers (and perhaps GitKraken) - but for now, GitHub rules and the other hosts are unsupported.
       
      Links
      Github: ModuleReleaseNotes
      PW Module Repository: Here (pending?)