Admin Controllers en modulos — guia completa

Actualizado: 2024-12-01

Los AdminController de modulos son la forma clasica de crear paginas de gestion en el Back Office de PrestaShop. Extendiendo ModuleAdminController obtienes CRUD completo de forma casi automatica cuando lo combinas con un ObjectModel.

#Estructura del AdminController

controllers/admin/AdminMyModuleItemsController.php
php
<?php

if (!defined('_PS_VERSION_')) { exit; }

/**
 * AdminController del modulo.
 * Ruta del archivo: modules/mymodule/controllers/admin/AdminMyModuleItemsController.php
 */
class AdminMyModuleItemsController extends ModuleAdminController
{
    public function __construct()
    {
        // Nombre de la tabla (sin prefijo) y clase del ObjectModel
        $this->table      = 'mymodule_item';
        $this->className  = 'MyModuleItem';
        $this->identifier = 'id_mymodule_item';
        $this->bootstrap  = true;

        // Columnas del listado
        $this->fields_list = [
            'id_mymodule_item' => ['title' => 'ID',     'align' => 'center', 'width' => 50],
            'name'             => ['title' => 'Nombre', 'width' => 'auto'],
            'active'           => ['title' => 'Activo', 'active' => 'status', 'type' => 'bool', 'align' => 'center'],
        ];

        parent::__construct();

        $this->bulk_actions = [
            'delete' => [
                'text'    => $this->l('Eliminar seleccionados'),
                'confirm' => $this->l('¿Seguro que deseas eliminar?'),
                'icon'    => 'icon-trash',
            ],
        ];
    }
}

#CRUD automatico con ObjectModel

Cuando $this->className apunta a un ObjectModel valido y $this->table coincide con su tabla, el controller hereda automaticamente las operaciones list, add, edit, delete y toggle de activo/inactivo.

ObjectModel necesario para el CRUD automatico
php
<?php

if (!defined('_PS_VERSION_')) { exit; }

/**
 * Archivo: modules/mymodule/classes/MyModuleItem.php
 * (o src/Entity/MyModuleItem.php con autoload)
 */
class MyModuleItem extends ObjectModel
{
    public $name;
    public $description;
    public $active = true;
    public $date_add;
    public $date_upd;

    public static $definition = [
        'table'   => 'mymodule_item',
        'primary' => 'id_mymodule_item',
        'fields'  => [
            'name'        => ['type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 255, 'required' => true],
            'description' => ['type' => self::TYPE_HTML,   'validate' => 'isCleanHtml'],
            'active'      => ['type' => self::TYPE_BOOL,   'validate' => 'isBool'],
            'date_add'    => ['type' => self::TYPE_DATE,   'validate' => 'isDate'],
            'date_upd'    => ['type' => self::TYPE_DATE,   'validate' => 'isDate'],
        ],
    ];
}

#Personalizar renderList y renderForm

Personalizar el formulario de edicion (renderForm)
php
<?php

// Dentro de AdminMyModuleItemsController
public function renderForm(): string
{
    $this->fields_form = [
        'legend' => [
            'title' => $this->l('Item del modulo'),
            'icon'  => 'icon-cogs',
        ],
        'input' => [
            [
                'type'     => 'text',
                'label'    => $this->l('Nombre'),
                'name'     => 'name',
                'required' => true,
                'size'     => 50,
            ],
            [
                'type'  => 'textarea',
                'label' => $this->l('Descripcion'),
                'name'  => 'description',
                'rows'  => 5,
                'cols'  => 50,
                'autoload_rte' => true,  // TinyMCE
            ],
            [
                'type'   => 'switch',
                'label'  => $this->l('Activo'),
                'name'   => 'active',
                'values' => [
                    ['id'=>'active_on',  'value'=>1, 'label'=>$this->l('Si')],
                    ['id'=>'active_off', 'value'=>0, 'label'=>$this->l('No')],
                ],
            ],
        ],
        'submit' => [
            'title' => $this->l('Guardar'),
        ],
    ];

    return parent::renderForm();
}

#Registrar en el menu (Tab)

Registrar el AdminController en el menu desde install()
php
<?php

// En mymodule.php — instalar el Tab al instalar el modulo
public function install(): bool
{
    return parent::install() && $this->installAdminTab();
}

public function uninstall(): bool
{
    return $this->uninstallAdminTab() && parent::uninstall();
}

private function installAdminTab(): bool
{
    $tab = new Tab();
    $tab->active     = 1;
    $tab->class_name = 'AdminMyModuleItems';
    $tab->module     = $this->name;
    $tab->id_parent  = (int) Tab::getIdFromClassName('IMPROVE');
    $tab->icon       = 'extension';

    foreach (Language::getLanguages() as $lang) {
        $tab->name[$lang['id_lang']] = 'Mis Items';
    }

    return (bool) $tab->save();
}

private function uninstallAdminTab(): bool
{
    $tabId = (int) Tab::getIdFromClassName('AdminMyModuleItems');
    if ($tabId) {
        $tab = new Tab($tabId);
        return (bool) $tab->delete();
    }
    return true;
}
Descargar en Markdown Pensado para pegar en ChatGPT, Claude u otra IA. Incluye solo el contenido de esta pagina.