Dashboard Widget With Dynamic JSON Content

Hello everyone,

I wrote a short article about how I came up with a solution to the following:

Send a message to multiple Kirby CMS Panels at once. Could be used for:

  • Announcing that a newer version of a Plugin or Theme is available
  • Other important announcements

My code might be a little hell for you folks, but I hope the concept might be useful for someone and the code itself could be improved.

:point_right: Here is the full article
(Should I paste the full article here, by the way?)

May I suggest some code changes?

Widget file

<?php
return array(
    'title' => 'Raport Version',
    'html'  => function() {


        // Fetch Information
        // ------------------------------------
        $url = 'http://example.com/raport-version.json';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        curl_close($ch);
        $arr = json_decode($data, true);

        // load template and pass variables to it
        return tpl::load(__DIR__ . DS . 'raport.html.php', [
          'customMessage'  => $arr['custom_message'],
          'currentVersion' => $arr['current_version'],
          'upgradeURL'     => $arr['upgrade_url'],
          'localVersion'   => floatval(kirby()->site()->raportVersion()->value()),
          'needUpdate'     => false
          ]);
    }
);

Template:

<!--Print Information -->

<p>Current version: <strong><?= $localVersion ?></strong></p>

<?php if( $localVersion < $currentVersion ): ?>
    <div class="upgrade">
    <p>There is a newer version of Raport available<p>
    <a href="<?= $upgradeURL ?>" target="_blank">
    Update now to <strong>version  <?= $currentVersion ?> &rarr;</strong></a>
    </div>
<?php else: ?>
    <div class="ok">You are using the latest version. Enjoy!</div>
<?php endif ?>

<?php
// Custom Message
// ------------------------------------
if( $customMessage != '' ): ?>
  <div><?= $customMessage ?></div>
<?php endif ?>

<style>
.upgrade {
  border: 1px solid #e57910;
  color: #e57910;
  padding: 10px;
  border-radius: 3px;
  text-align: center;
  margin: 10px 0;
  clear: both;
  line-height: 1.5;
}

.ok {
  border: 1px solid green;
  padding: 10px;
  border-radius: 3px;
  text-align: center;
  margin: 10px 0;
  clear: both;
  color: green;
  line-height: 1.5;
}
</style>

On a side note: Why does your JSON return a multi-dimensional array so that you have to fetch it with $arr[0][$key]?

Thanks a billion, Sonja, your changes are more than welcome!
I changed the Git Gists and added a note to the article.

About the multi-dimensional array - honestly, there’s no particular reason for it in the sample code :slight_smile:

1 Like