Tag Archives: Programming

Joomla 3 Module with selectable template output

I’ve been working on a Joomla based website the past few weeks, and getting my head around the world according to Joomla 3.  I’ve been using modules for various parts of the web pages, and today I wanted to have a module adjust is output based on a configuration setting.

In the Joomla backend, you create a ‘module’ instance that acts as a conduit for the actual module code.  You specify where and when that instance will appear on the user pages. There are quite a lot of parameters you can specify, but I needed to be able to switch how the module renders its content.

To do this I added an entry to the modules XML file in the <config> section:


  
    
      ;    
 

This added an entry ‘Layout’ in the Advanced tab for my module instance in module manager.

I also duplicated the default.php file in my module tmpl folder, and named it alt-view.php for now.  With that done, going to the advanced tab in module manager for my module, I could select either default or alt-view as the layout.

In order for the module to use the right template, I needed to modify the main module code.  My module is called cfviewposts, so mod_cfviewposts.php contains the main entry point for the module.

The last line of the PHP code loads the template and then execution rolls into it.  I changed it to the following line

require JModuleHelper::getLayoutPath('mod_cfviewposts',$params->get("layout","default"));

This pulls the ‘layout’ param from the module parameters, and if it’s not present, defaults to ‘default’ which will load default.php from mod_cfviewposts/tmpl.

So now I can create a 2nd instance of my module, and using the newly minted advanced configuration option, select the alternate output when that module is displayed.

Removing empty entries in a PHP array

I’m working on some PHP code right now, and I need to split a URI path and recombine it with some changes.  However, I ran into an issue using explode.  This is what I had:

$parts = explode('/',$path);

This worked as expected, unless the URI ended with a ‘/’, in which case I ended up with an empty string as the last item.  Also, if it started with a ‘/’ then I’d get an empty string at the start.  I decided to fix this using array_filter with the default predicate, like so:

$parts = array_filter(explode('/',$path));

Job done, right? Nope! Turns out array_filter doesn’t reindex anything, so my array ended up with no [0] entry, and $parts[count($parts)-1] didn’t return the last entry anymore.  I needed to rebuild the array with new indexes.  Solved it by using array_values like so:

$parts = array_values(array_filter(explode('/',$path)));

If it was mission critical, maybe it would be more efficient to create an iterator that loops over the exploded array and appends any non-zero length strings to a new array, but I’ll save that for another day.

JavaScript page refresh timer

I wanted a web page I’ve been working on to auto-refresh, but not just after a certain time has elapsed, but when the clock is just past a quarter hour interval (i.e. x:15, x:30, x:45, x:00).

It’s pretty straightforward, but as I was searching around, it seems to be a pretty common question, so figured I’d put up my own answer here:

 function setAutoRefresh()
 {
   var interval = 15*60*1000; //every 15 mins...
   var timeNow = new Date().getTime();
   var nextInterval = (Math.floor(timeNow/interval)+1) * interval + 10000; //next time interval, plus 10 seconds...
   var nextIntDate = new Date();
   nextIntDate.setTime(nextInterval);
   console.log("Next timeout tick: " + nextIntDate.toLocaleTimeString());
   autoRefreshTimer = setTimeout(function(){
   console.log("Auto-refresh: " + new Date().toLocaleTimeString());
   reloadPage();
   },nextInterval - new Date().getTime());
 }

So we round up the current time in ms to the next 15 min interval, and add 10,000 so our event triggers 10 seconds after the interval (I have another process that ticks every 5 mins and updates the DB table this web page pulls from, so I wanted to make sure I got the latest data).

The var autoRefreshTimer is global and can be used to cancel the timeout timer when the page becomes hidden.

The var nextIntDate is only used for the console log, and can be removed if you don’t need that.

The function reloadPage resends all my ajax calls to reload the different data on the web page and then calls setAutoRefresh when it’s all done.

Hope that all makes sense.

 

Json_encode and PHP 5.2.17

A server I push PHP scripts to is still running PHP 5.2.17 – its insanely old, almost 5 years!

I discovered that if I try to use that version of json_encode and pass it a string with unicode characters, I get nulls back where I should have UTF-8 encoded strings!  The code works fine on my local server, running PHP 7.0.15.

The fix for this is pretty simple, but worth noting for future reference:

 $text = utf8_encode($row[$key]);
 array_push($items,$text);

Where $row is an assoc. array and $key points to the value I want to push into my array which in turn is encoded with:

$json = json_encode($items);

Without the ‘utf8_encode’ I just get nulls in my encoded string 🙁

Javascript, UTC datetime and formatting oh my…

I’ve been working on a project to display data stored in a MySQL database using the Google Graph API.  I’ve done this before, but this time I need to display the time the MySQL entry was created.  The DB row contains this information as a MySQL timestamp field, and is returned as a string when I fetch it, for example:

2017-07-09 02:30:00

This is in UTC, and as I’ve discovered, the PHP script has no idea of what timezone the browser is in, so either I need to pass that from JavaScript, or hand the UTC times back to the browser and let it take care of the conversion.  I decided it would be best to let the browser handle it (for now), and immediately discovered the confusion around formatting a Date string with JavaScript.

To me, this seems pretty basic, and I really don’t understand why it was omitted from the language.  There are a lot of libraries out there that will do this for you, but I ended up using jQuery, as I was already using it for the AJAX and graphing support.

jQuery provides the .datepicker class, which includes a date formatter.  I just needed the month and day, the month needs to be a short string, while the day is a number without any leading zeros.  I used the following:

$.datepicker.formatDate("M-d",utcTime)

Where utcTime is a Date object that’s been created from the MySQL string with:

var dt = new Date(Date.parse(item[0] + "Z"));

I append the Z to the MySQL string, so JavaScript knows its a UTC time.

At the time I did this, there is no option for handling Time within the standard jQuery package, so I added that manually, padding with a leading ‘0’ as needed, with the final date/time string being created with:

return $.datepicker.formatDate("M-d",utcTime) + " "
        + ("0" + utcTime.getHours()).slice(-2) + ":"
        + ("0" + utcTime.getMinutes()).slice(-2);

Note: I could have had .datepicker parse the string, but it wouldn’t have given me the time portion, so I do that in a separate step.