Creating Extensions for FacturaScripts

Extend existing functionality without modifying the base code

What are Extensions?

Extensions let you modify and expand FacturaScripts' behavior without altering the system's core files. They're ideal for adding custom fields, modifying views or extending functionality.

🎯 Advantages of Extensions

  • Don't modify core code
  • Compatible with updates
  • Easy to maintain
  • Reusable
  • Safe and stable

📦 Example: ModCliente

  • Function: Add "Capital Social" field
  • Method: Extension of the Cliente model
  • Files: 5 essential components
  • Compatibility: FacturaScripts 2025+

Structure of an Extension

A basic extension requires these files organized in a specific structure:

Plugins/
└── ModCliente/
    ├── Extension/
    │   └── Table/
    │       └── cliente.xml
    │   └── XMLView/
    │       ├── EditCliente.xml
    │       └── ListCliente.xml
    ├── Init.php
    └── facturascripts.ini

Step 1: Plugin Configuration (facturascripts.ini)

Define the extension's basic information:

[plugin]
name = ModCliente
description = Mod expansión de plugin
version = 0.1
min_version = 2025

💡 Important Note

For extensions, the min_version must match the FacturaScripts version you're using to ensure compatibility.

Step 2: Initialization File (Init.php)

This file manages the extension's lifecycle:

<?php

namespace FacturaScripts\Plugins\ModCliente;

use FacturaScripts\Core\Template\InitClass;

class Init extends InitClass
{
    public function init(): void
    {
        $this->loadExtension(new Extension\Controller\ListCliente());
    }

    public function uninstall(): void
    {
        // Limpieza de datos o configuraciones al desinstalar el plugin
    }

    public function update(): void
    {
        // Ajustes al instalar o actualizar el plugin
    }
}

🔧 Main Functions

  • init(): Loads extensions when the plugin is activated
  • uninstall(): Cleanup on uninstall
  • update(): Migrations between versions

Step 3: Controller Extension

Create the class that extends the original controller's behavior:

<?php

namespace FacturaScripts\Plugins\ModCliente\Extension\Controller;

use FacturaScripts\Core\Base\Extension;

class ListCliente extends Extension
{
    public function run(): void
    {
        // Aquí puedes modificar el comportamiento del controlador ListCliente        // Por ejemplo, añadir filtros personalizados, modificar datos, etc.    }
}

Location: Extension/Controller/ListCliente.php

Step 4: Extend the Model (cliente.xml)

Add new fields to the existing table using XML:

<?xml version="1.0" encoding="UTF-8"?>
<table>
    <column>
        <name>capitalsocial</name>
        <type>Integer</type>
        <default></default>
    </column>
</table>

📋 Available Data Types

  • Integer: Whole numbers
  • Double: Decimal numbers
  • Varchar: Short text (specify length)
  • Text: Long text
  • Boolean: True/False
  • Date/DateTime: Dates

Step 5: List View (ListCliente.xml)

Define how the new field is displayed in the client list:

<?xml version="1.0" encoding="UTF-8"?>
<view>
    <columns>
           <column name="Capital social" order="189">
              <widget type="money" fieldname="capitalsocial" />
           </column>
    </columns>
</view>

🎨 Available Widget Types

  • text: Simple text field
  • money: Formatted monetary field
  • number: Numeric field
  • checkbox: Checkbox
  • date: Date picker
  • select: Dropdown list

Step 6: Edit View (EditCliente.xml)

Define how the new field is edited in the client form:

<?xml version="1.0" encoding="UTF-8"?>
<view>
    <columns>
        <group name="contact" title="contact-info" numcolumns="12">
           <column name="Capital social">
              <widget type="money" fieldname="capitalsocial" />
           </column>
        </group>
    </columns>
</view>

📐 Organization into Groups

Groups let you organize fields into logical sections. The numcolumns attribute defines the width in the grid system (1-12).

Installation Flow

1. Create the directory structure

Create the Plugins/ModCliente/ folder with all the necessary subdirectories.

2. Copy the files

Place each file in its corresponding location according to the structure shown.

3. Activate the plugin

  1. Go to "Administration → Plugins"
  2. Find "ModCliente" in the list
  3. Click "Activate"
  4. FacturaScripts will automatically create the column in the database

4. Verifying the installation

  • Navigate to "Clients → Clients"
  • Verify the "Capital social" column appears
  • Edit a client and check that the field is available

Advanced Example: Complete Extension

Let's create a more complex extension that adds multiple fields and functionality:

Extended model (cliente.xml)

<?xml version="1.0" encoding="UTF-8"?>
<table>
    <column>
        <name>capitalsocial</name>
        <type>Integer</type>
        <default>0</default>
    </column>
    <column>
        <name>fechaconstitucion</name>
        <type>Date</type>
        <default></default>
    </column>
    <column>
        <name>esempresa</name>
        <type>Boolean</type>
        <default>false</default>
    </column>
    <column>
        <name>notasinternas</name>
        <type>Text</type>
        <default></default>
    </column>
</table>

Extended controller (ListCliente.php)

<?php

namespace FacturaScripts\Plugins\ModCliente\Extension\Controller;

use FacturaScripts\Core\Base\Extension;

class ListCliente extends Extension
{
    public function run(): void
    {
        // Añadir filtro personalizado para empresas
        $this->getController()->addFilterSelect('esempresa', 'Tipo', [
            '' => 'Todos',
            'true' => 'Solo empresas',
            'false' => 'Solo personas'
        ]);
        
        // Modificar la consulta base
        $this->getController()->addSearchFields(['notasinternas']);
    }
    
    public function beforeRender(): void
    {
        // Modificaciones antes de renderizar la vista        $view = $this->getController()->getView('ListCliente');
        if ($view) {
            // Personalizar la vista        }
    }
}

Common Troubleshooting

Field doesn't appear

  • Verify the plugin is activated
  • Check the field names in the XML files
  • Check the logs in MyFiles/Logs/
  • Force reload with Ctrl+F5

Database errors

  • Verify the model's XML syntax
  • Check that the data type is valid
  • Check that there are no naming conflicts
  • Deactivate and reactivate the plugin

Extension doesn't load

  • Verify the namespace in Init.php
  • Check the extension's path
  • Verify the class extends correctly
  • Confirm the loadExtension method is called

Best Practices for Extensions

📁 Structure and naming

  • Use "Mod" prefixes for extensions
  • Keep names descriptive
  • Organize files by functionality
  • Document your changes

🔧 Development

  • Test in a development environment
  • Handle errors gracefully
  • Respect the existing flow
  • Use appropriate data types

🚀 Performance

  • Avoid very heavy extensions
  • Optimize database queries
  • Use cache when appropriate
  • Minimize expensive hooks

Next Steps and Resources

🚀 Advanced Features

  • Create custom hooks
  • Extend multiple controllers
  • Add custom validations
  • Integrate with external APIs

🛠️ Useful Tools

  • XML validator for model files
  • PHP Code Sniffer for code standards
  • Database manager to view changes
  • Browser DevTools for debugging

Conclusion

Extensions are a powerful tool for customizing FacturaScripts without compromising the system's upgradability. By following this guide, you can add features specific to your business while maintaining stability and compatibility with future versions.

✅ You're ready to create your own extensions!

Start with simple extensions and gradually move toward more complex functionality. Always remember to test in a development environment before deploying to production.