Skip to main content

Let's use ChatGPT to create a simple module for Joomla4

| Gianluca Gabella | Joomla!
share on facebook share on twitter share on linkedin

Index:


ChatGPT is on everyone's lips: it can make conversation, create texts, summarise content and write scripts. But it can also invent and implement code: let's see how it fares with PHP and the Joomla4 framework!

What is ChatGPT?

For those of you who have been disconnected from planet earth for the last month (or for those of you who come to this post in 10 years...) here is a brief summary of the current situation: for the last few weeks, the ChatGPT tool developed by OpenAI has been all over the web. The texts it generates range from the astonishing to the sketchy, sometimes even with not inconsiderable logical and content errors, but it cannot be denied that it is a very interesting tool that lays the foundations for our future relationship with Artificial Intelligence.

To chat with ChatGPT simply click here: https://chat.openai.com/ and register

How can we be helped by an AI in our work?

Despite many people saying they are worried ("it will steal our jobs!", "it will be impossible to continue working with such competition!", ...) I find this tool actually a gigantic opportunity, to be understood well and used in the right ways. Obviously we can't just tell them 'create this text' or 'generate a catchy claim': human creativity is still many leagues above the results you get with ChatGPT, but we can certainly get some help.

For example in generating code.

How many times have we scoured the Internet looking for a way to generate a Regex string? Well, ChatGPT can create it for us in less than 10 seconds.
How many times have we ended up on StackOverflow looking for answers about a certain compilation error? Well, with ChatGPT you can have a thorough debug of your code in no time.

At this point, how can we get help writing, for example, a simple module for Joomla?

What are Joomla extensions and how are they subdivided?

Let us first try to understand what 'Joomla module' means.

The famous CMS is based on extensions that can be divided into:

  • Components
  • Plugins
  • Modules

Components are packages (which may also contain linked modules and plugins) that serve to add new functionality to a CMS. For example, Virtuemart is a component used to add e-commerce functionality to a Joomla site.

Plugins are functions that can be called at any time during the generation of a Joomla page, either frontend or backend. They are 'hooked' to trigger events: that is, they can be called when a certain thing happens. Example: there are plugins that only 'start' when a user registers. Within them there will then be functions that are only called when the 'user registration' event occurs.

Modules, on the other hand, are the simplest extensions of Joomla. They are 'blocks of code' that can also be stand-alone and can be loaded from the frontend template anywhere on the page. For example, the most common module is the one that in Italian is called 'custom' and simply provides a text editor: we can create this module and load it into the side column (for example) of our site, on any page we wish.

Let's create a simple form with ChatGPT

For this test, I wanted to simply create a form for several reasons:

  • First of all because it requires less code than a component or plugin;
  • Because it is easier to test it 'live';
  • Because in general it is much easier to need a 'baked and eaten' module and not a plugin or (worse) a component that requires time and good programming skills.

Well, let us begin.

I first asked ChatGPT: "can you create me a Joomla4 module that prints out a list of all registered users?"

The answer was generic:

risposta chat gpt

The answer is correct (in the sense that it 'works'), but it is not optimal: Joomla uses the MVC paradigm which requires a well-defined structure. This means that you also need a template (whose override can be created in the future) and possibly a helper.php file for handling functions.

Of these things there is no trace.

But let's move on, we really want to see some code. Let's see what ChatGPT is capable of producing, so I asked him: "can you write me the php code?"

At this point we went more specific, here is the answer:

risposta chatgpt codicephp

In case you want to test the result yourself, here is the code written above to copy/paste:

defined('_JEXEC') or die;

class ModUserListHelper
{
    public static function getUsers()
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('id, name, username, email');
        $query->from($db->quoteName('#__users'));
        $db->setQuery($query);
        $results = $db->loadObjectList();
        return $results;
    }
}

Great, we have code!

However, we still don't know if it works or not (actually we can already get an idea, but we can't test it by hand). To do this we need to have everything we need to create a real Joomla module.

Let's generate the XML file

The first thing we need in order to install a Joomla extension is an XML file in which we put all the information of our extension.
I asked him to also generate the XML for me using "List all users" as the module name:

xml modulo chat gpt

The generated code is as follows (wait to copy it! There is an error which we resolve a little further down!):

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="4.0" method="upgrade">
    <name>Lista tutti gli utenti</name>
    <author>Tu nome</author>
    <creationDate>Oggi</creationDate>
    <copyright>Copyright (C) 2023 Tu nome. Tutti i diritti riservati.</copyright>
    <license>GNU General Public License version 2 o successiva</license>
    <authorEmail>La tua email</authorEmail>
    <authorUrl>Il tuo sito web</authorUrl>
    <version>1.0.0</version>
    <description>Modulo che stampa una lista di tutti gli utenti iscritti.</description>
    <files>
        <filename module="mod_userlist">mod_userlist.php</filename>
        <filename>mod_userlist.xml</filename>
    </files>
    <config>
    </config>
</extension>

Obviously we have to go and edit all the XML fields that have been generated with placeholders, so <creationDate>, <authorEmail>, etc...

I now have two files:

  • A PHP with code generated by GPT chat
  • An XML with all the necessary information  

However, I have no indication of what these files should be called and how to actually install the package on a Joomla4.
No matter: by definition, there must be at least two files:

  • mod_userlist.php
  • mod_userlist.xml

(as is actually suggested within the generated XML) and must be within an archive called mod_userlist.zip

Installing the module on a Joomla 4 site

Well, we now have our ZIP with the two files inside. If we try to install it, we get an error:

errore installazione modulo

Doing some debugging, I discovered that an attribute of the 'extension' tag of the XML -> client='site' is missing:

<extension type="module" version="4.0" method="upgrade" client="site" >

Once inserted into the original XML, the module installs correctly:

modulo lista di tutti gli utenti

Let's test our module

The module generated by ChatGPT is obviously and intentionally very basic: if you enter the module you won't find any options and various configurations.
No harm done: creating a complex or 'perfect' module is not the purpose of this guide, we just need to know if ChatGPT is 'able to steal our work'. :-D

So let's publish the module and assign it to all pages.

If we try to load the form on one of our web pages, however, nothing will be displayed. How come?

It was actually expected: the piece of PHP code indicated by ChatGPT does not generate any output. It makes a query to the database and saves the results in the $results variable.
At this point the only way to 'see' if it works is to modify the PHP so that it generates some kind of output.

But let's let ChatGPT do that!

modulo lista di tutti gli utenti completo

Here is our complete output code!

You can either put it in a new zip and reinstall the package or simply change the PHP file on the server with a program like FileZilla.

If all went well, your module is now installed, working and visible from the frontend! (I masked the user names for safety, but they printed correctly)

output modulo chatgpt

Conclusions

  • Was ChatGPT able to create a module for Joomla4 from scratch?
    Technically no: it generated an error in the XML that did not allow the module to be installed. We had to correct it by hand to avoid 'Internal Server Error' errors during installation.

  • Did ChatGPT gave me a hand in creating the module?
    Absolutely YES! The whole part of the PHP code is correct in the sense that it does what it is supposed to do: print out a list of the users of the website.

  • Is the module created, which works, done properly?
    No, we are a long way from a properly made module: the whole MVC and template part (for overrides) has been ignored and a module made in this way shows a decided lack of knowledge of the Joomla framework.

  • So ChatGPT is going to steal my job?
    If you are a programmer who does things in a hurry without studying them, implementing them properly and testing them, maybe yes... if you are a developer who follows the good programming rules of a Joomla extension then you can rest assured, ChatGPT won't steal your work but it can certainly give you a hand in creating complex queries or Regex rules! :-)

If you liked this article, please share it!

share on facebook share on twitter share on linkedin
condividi su Facebookcondividi su Twittercondividi su LinkedIncondividi su WhatsAppcondividi su Telegram