Skip to content
TheChatArchiveThe Chat Archive
o3-mini· OpenAIHugging Face LMArena Human Preference 140K

Genérame un módulo de Prestashop versión 8+ que genere un crud de eventos, también un…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.0-flash-thinking-exp-01-21’s answer.
  1. User

    Genérame un módulo de Prestashop versión 8+ que genere un crud de eventos, también un custom hook para poder mostrar un grid de esos eventos en el .tpl que yo quiera

  2. Assistant

    A continuación te proporciono un ejemplo básico de un módulo para Prestashop 8+ que implementa un CRUD de “eventos” y define un hook personalizado para mostrar un grid (tabla) de eventos en cualquier plantilla (.tpl). En este ejemplo se incluye la creación de la tabla, la lógica para añadir/editar/eliminar registros desde la configuración del módulo (en el Back Office) y la declaración del custom hook para que lo invoques en tus tpl. Puedes adaptar y ampliar el código según lo necesites.


    Estructura del módulo

    La estructura mínima del módulo podría ser la siguiente:

    /modules
      /eventcrud
        eventcrud.php
        index.php
        /views
          /templates
            /hook
              eventGrid.tpl
    

    Nota: El archivo index.php suele ser un “placeholder” de seguridad para evitar listar el contenido del directorio.


    Archivo principal del módulo: eventcrud.php

    Crea el archivo /modules/eventcrud/eventcrud.php con el siguiente contenido:

    <?php
    if (!defined('_PS_VERSION_')) {
        exit;
    }
    
    class EventCrud extends Module
    {
        public function __construct()
        {
            $this->name = 'eventcrud';
            $this->tab = 'administration';
            $this->version = '1.0.0';
            $this->author = 'TuNombre';
            $this->need_instance = 0;
            $this->bootstrap = true;
    
            parent::__construct();
    
            $this->displayName = $this->l('Módulo CRUD de Eventos');
            $this->description = $this->l('Módulo para gestionar eventos con funcionalidades CRUD.');
            $this->ps_versions_compliancy = array('min' => '1.7.0.0', 'max' => _PS_VERSION_);
        }
    
        public function install()
        {
            if (!parent::install() 
                || !$this->registerHook('displayEventGrid')
                || !$this->installDB()
            ) {
                return false;
            }
            return true;
        }
    
        public function uninstall()
        {
            if (!parent::uninstall() || !$this->uninstallDB()) {
                return false;
            }
            return true;
        }
    
        /**
         * Crea la tabla de eventos.
         */
        protected function installDB()
        {
            $sql = "CREATE TABLE IF NOT EXISTS `" . _DB_PREFIX_ . "event` (
              `id_event` INT UNSIGNED NOT NULL AUTO_INCREMENT,
              `title` VARCHAR(255) NOT NULL,
              `description` TEXT,
              `event_date` DATETIME NOT NULL,
              PRIMARY KEY (`id_event`)
            ) ENGINE=" . _MYSQL_ENGINE_ . " DEFAULT CHARSET=utf8;";
    
            return Db::getInstance()->execute($sql);
        }
    
        /**
         * Elimina la tabla de eventos.
         */
        protected function uninstallDB()
        {
            $sql = "DROP TABLE IF EXISTS `" . _DB_PREFIX_ . "event`;";
            return Db::getInstance()->execute($sql);
        }
    
        /**
         * Hook personalizado para mostrar el grid de eventos.
         * Para usarlo en un tpl, basta con llamar:
         *    {hook h='displayEventGrid'}
         */
        public function hookDisplayEventGrid($params)
        {
            $events = Db::getInstance()->executeS("SELECT * FROM `" . _DB_PREFIX_ . "event` ORDER BY event_date DESC");
            $this->context->smarty->assign('events', $events);
            return $this->display(__FILE__, 'views/templates/hook/eventGrid.tpl');
        }
    
        /**
         * Configuración del módulo (Back Office) donde se podrá gestionar el CRUD.
         */
        public function getContent()
        {
            $output = '';
    
            // Proceso para añadir o editar un evento.
            if (Tools::isSubmit('submitEvent')) {
                $id_event    = Tools::getValue('id_event');
                $title       = Tools::getValue('title');
                $description = Tools::getValue('description');
                $event_date  = Tools::getValue('event_date');
    
                if ($id_event) {
                    // Actualiza el evento existente.
                    Db::getInstance()->update('event', array(
                        'title'       => pSQL($title),
                        'description' => pSQL($description),
                        'event_date'  => pSQL($event_date)
                    ), 'id_event = ' . (int)$id_event);
                    $output .= $this->displayConfirmation($this->l('Evento actualizado correctamente.'));
                } else {
                    // Inserta un nuevo evento.
                    Db::getInstance()->insert('event', array(
                        'title'       => pSQL($title),
                        'description' => pSQL($description),
                        'event_date'  => pSQL($event_date)
                    ));
                    $output .= $this->displayConfirmation($this->l('Evento añadido correctamente.'));
                }
            }
    
            // Proceso para eliminar un evento.
            if (Tools::isSubmit('deleteEvent')) {
                $id_event = (int)Tools::getValue('deleteEvent');
                Db::getInstance()->delete('event', 'id_event = ' . $id_event);
                $output .= $this->displayConfirmation($this->l('Evento eliminado correctamente.'));
            }
    
            // Muestra la lista de eventos y el formulario para añadir/editar.
            $events = Db::getInstance()->executeS("SELECT * FROM `" . _DB_PREFIX_ . "event` ORDER BY event_date DESC");
            $output .= $this->renderList($events);
            $output .= $this->renderForm();
    
            return $output;
        }
    
        /**
         * Renderiza la lista de eventos.
         */
        private function renderList($events)
        {
            $html = '<h2>' . $this->l('Listado de Eventos') . '</h2>';
            $html .= '<table class="table">';
            $html .= '<thead>
                        <tr>
                          <th>' . $this->l('ID') . '</th>
                          <th>' . $this->l('Título') . '</th>
                          <th>' . $this->l('Descripción') . '</th>
                          <th>' . $this->l('Fecha del Evento') . '</th>
                          <th>' . $this->l('Acciones') . '</th>
                        </tr>
                      </thead>';
            $html .= '<tbody>';
            foreach ($events as $event) {
                $html .= '<tr>
                            <td>' . $event['id_event'] . '</td>
                            <td>' . $event['title'] . '</td>
                            <td>' . $event['description'] . '</td>
                            <td>' . $event['event_date'] . '</td>
                            <td>
                              <a href="' . $_SERVER['REQUEST_URI'] . '&editEvent=' . $event['id_event'] . '">' . $this->l('Editar') . '</a> |
                              <a href="' . $_SERVER['REQUEST_URI'] . '&deleteEvent=' . $event['id_event'] . '" onclick="return confirm(\'' . $this->l('¿Estás seguro?') . '\');">' . $this->l('Eliminar') . '</a>
                            </td>
                          </tr>';
            }
            $html .= '</tbody></table>';
    
            return $html;
        }
    
        /**
         * Renderiza el formulario para añadir o editar un evento.
         */
        private function renderForm()
        {
            $id_event = Tools::getValue('editEvent');
            $defaultData = array(
                'id_event'    => '',
                'title'       => '',
                'description' => '',
                'event_date'  => date('Y-m-d H:i:s')
            );
    
            if ($id_event) {
                $event = Db::getInstance()->getRow("SELECT * FROM `" . _DB_PREFIX_ . "event` WHERE id_event = " . (int)$id_event);
                if ($event) {
                    $defaultData = $event;
                }
            }
    
            $html = '<h2>' . $this->l('Añadir / Editar Evento') . '</h2>
                    <form method="post" action="' . $_SERVER['REQUEST_URI'] . '">
                        <input type="hidden" name="id_event" value="' . (int)$defaultData['id_event'] . '" />
                        <div class="form-group">
                            <label>' . $this->l('Título') . '</label>
                            <input type="text" name="title" value="' . htmlentities($defaultData['title'], ENT_COMPAT, 'UTF-8') . '" class="form-control" required/>
                        </div>
                        <div class="form-group">
                            <label>' . $this->l('Descripción') . '</label>
                            <textarea name="description" class="form-control" rows="5" required>' . htmlentities($defaultData['description'], ENT_COMPAT, 'UTF-8') . '</textarea>
                        </div>
                        <div class="form-group">
                            <label>' . $this->l('Fecha del Evento') . '</label>
                            <input type="datetime-local" name="event_date" value="' . date('Y-m-d\TH:i', strtotime($defaultData['event_date'])) . '" class="form-control" required/>
                        </div>
                        <button type="submit" name="submitEvent" class="btn btn-primary">' . $this->l('Guardar') . '</button>
                    </form>';
    
            return $html;
        }
    }
    

    Explicación rápida del código anterior:

    • Instalación y desinstalación:
    Se crea (o elimina) la tabla ps_event en la función installDB() y uninstallDB().

    • Hook personalizado:
    La función hookDisplayEventGrid() asigna la lista de eventos a Smarty y carga el tpl que hemos creado.

    • Back Office (getContent):
    Se procesa el formulario para añadir o editar eventos y se muestra, junto a una lista de eventos, una tabla con las operaciones disponibles (editar/eliminar).


    Archivo de plantilla para el hook: views/templates/hook/eventGrid.tpl

    Crea el archivo /modules/eventcrud/views/templates/hook/eventGrid.tpl con el siguiente contenido:

    <div class="event-grid">
      <h3>{l s='Próximos Eventos' mod='eventcrud'}</h3>
      <table class="table">
        <thead>
          <tr>
            <th>{l s='ID' mod='eventcrud'}</th>
            <th>{l s='Título' mod='eventcrud'}</th>
            <th>{l s='Descripción' mod='eventcrud'}</th>
            <th>{l s='Fecha del Evento' mod='eventcrud'}</th>
          </tr>
        </thead>
        <tbody>
          {if isset($events) && $events|@count > 0}
            {foreach from=$events item=event}
              <tr>
                <td>{$event.id_event}</td>
                <td>{$event.title}</td>
                <td>{$event.description}</td>
                <td>{$event.event_date}</td>
              </tr>
            {/foreach}
          {else}
            <tr>
              <td colspan="4">{l s='No se encontraron eventos.' mod='eventcrud'}</td>
            </tr>
          {/if}
        </tbody>
      </table>
    </div>
    

    Nota: Puedes personalizar el HTML y los estilos CSS según tus necesidades.


    Archivo index.php (opcional)

    Para evitar el acceso directo al directorio, crea un archivo /modules/eventcrud/index.php con el siguiente contenido:

    <?php
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Location: ../");
    exit;
    

    Uso del hook personalizado en tus plantillas

    Una vez instalado el módulo, puedes mostrar el grid de eventos en cualquier plantilla .tpl (ya sea en un módulo o tema) usando:

    {hook h='displayEventGrid'}
    

    Esto inyectará el HTML generado por el hook, mostrando la tabla de eventos.


    Instalación

    1. Sube la carpeta eventcrud a la carpeta /modules de tu instalación de Prestashop.

    2. Instala el módulo desde el Back Office en la sección de Módulos y Servicios.

    3. Accede a la configuración del módulo para gestionar el CRUD de eventos.

    4. Utiliza el hook en tus plantillas donde lo necesites.


    Este es un ejemplo básico para iniciarte. Dependiendo de tus necesidades podrías querer separar aún más la lógica (por ejemplo, utilizando controllers administrativos dedicados, validaciones adicionales o una solución basada en Symfony) y aplicar estilos o funcionalidades JavaScript según se requiera. ¡Espero que te sea de ayuda!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.