Skip to content

10. Custom PHP file

JoomlaBoat, LLC edited this page Dec 9, 2024 · 12 revisions

Custom PHP Event Handler for Custom Tables in Joomla

Overview

Custom Tables allows you to execute custom PHP code when users perform specific actions on records (save, refresh, publish, or unpublish). This is accomplished through a custom PHP file with a process() function.

File ## Setup

Create a new PHP file in: /components/com_customtables/customphp/ Name convention: Choose a descriptive name (e.g., MyCustomPHPFileName.php) File structure requirements:

Must contain a class matching the filename Class must extend CustomPHP Must implement the process() method

Code Template

<?php
namespace CustomTables;

use Joomla\CMS\Factory;
use Joomla\Database\DatabaseInterface;

class MyCustomPHPFileName extends CustomPHP
{
    private DatabaseInterface $db;

    public function __construct(CT &$ct, string $action)
    {
        parent::__construct($ct, $action);
        $this->db = Factory::getContainer()->get('db');
    }
   
    public function process(?array $row, ?array $row_old): void
    {
        // Available actions: create, refresh, update, delete
    
        switch($this->action) {
            case 'refresh':
                if (isset($row['id'])) {
                    $query = $this->db->getQuery(true)
                        ->update($this->db->quoteName('#__customtables_table_products'))
                        ->set($this->db->quoteName('ct_status') . ' = ' . $this->db->quote('Updated'))
                        ->where($this->db->quoteName('id') . ' = ' . (int)$row['id']);
                    
                    $this->db->setQuery($query);
                    $this->db->execute();
                }
                break;

            case 'create':
                if (isset($row['id'])) {
                    $query = $this->db->getQuery(true)
                        ->update($this->db->quoteName('#__customtables_table_products'))
                        ->set($this->db->quoteName('ct_status') . ' = ' . $this->db->quote('This is a new record'))
                        ->where($this->db->quoteName('id') . ' = ' . (int)$row['id']);
                    
                    $this->db->setQuery($query);
                    $this->db->execute();
                }
                break;
        }
    }
}

Key Parameters

$row: Current record data (after changes) $row_old: Previous record data (before changes) $this->action: Current action being performed (create, refresh, update, delete)

Implementation Steps

Save your PHP file in the specified directory Upload to your website's /components/com_customtables/customphp/ folder Configure in Joomla backend:

Go to Components → Custom Tables → Tables Select your target table Navigate to the "Advanced" tab Select your custom PHP file from the dropdown

Select custom php file

Clone this wiki locally