Herramientas Informaticas

Etiqueta: GNU/LINUX Página 10 de 13

Comprimir y generar Respaldo en Windows automáticamente a una hora determinada

Para respaldar información importante como base de datos, documentos ETC, en muchos lugares se opta por las nubes como Google Drive, Dropbox ETC

Pero en ocasiones simplemente se opta por comprimir y pasarlo a otro equipo de computo

Para ello normalmente se usa cobian pero en una ocasión en nuestro caso falló y no alcanzaba a copiarse el archivo completo

Así que mostraremos como hacer el comando para que comprima y copie el archivo aunque exista problemas de intermitencia en la red

Para comprimir es necesario tener instalado winRar, ya instalado para comprimir usamos el siguiente comando, en este caso copiamos el respaldo de la base de datos de SQL Server

"C:\Program Files"\WinRAR\rar a -r -rr -v4700M "C:\respaldoDB\Respaldo%date:~-4,4%-%date:~-7,2%-%date:~-10,2%.rar" "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\"

Una vez comprimido se procede a realizar la copia en el otro equipo para ello usamos el siguiente comando, con robocopy en caso de que se caiga la red vuelve a intentar a copiarlo hasta que lo copia bien y completamente

robocopy "C:\respaldoDB" "\\IPDELOTROEQUIPO\Respaldo de prueba\carpetadestino"

Y procedemos a borrar el archivo creado en el equipo local

DEL /F /A C:\respaldoDB\Respaldo_%date:~-4,4%-%date:~-7,2%-%date:~-10,2%.rar

  

al final el archivo bat quedaría de la siguiente forma

"C:\Program Files"\WinRAR\rar a -r -rr -v4700M "C:\respaldoDB\Respaldo%date:~-4,4%-%date:~-7,2%-%date:~-10,2%.rar" "C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Backup\"

  

robocopy "C:\respaldoDB" "\\IPDELOTROEQUIPO\Respaldo de prueba\carpetadestino"

  

DEL /F /A C:\respaldoDB\Respaldo_%date:~-4,4%-%date:~-7,2%-%date:~-10,2%.rar

  

Ya listo para ejecutarlo a la hora que sea automáticamente con el programador de tareas de windows

Como convertir Web hecha en PHP8 con FrameWork CodeIgniter 4 en una APP de Escritorio

code

git clone https://github.com/electron/electron-quick-start.git

en el archivo package.json lo dejamos de la siguiente manera

	{

	"build": {
	"appId": "com.electron.example",
	"compression": "maximum"
	},
	"name": "XML2PDF CFDI",

	"version": "2.0.0",

	"description": "Una pequeña aplicación para convertir el CFDI XML a PDF",

	"main": "main.js",

	"compression": "maximum",

	"scripts": {

	"***": null,
	"pro:windows": "electron-builder --win"

	},
	"repository": "https://github.com/electron/electron-quick-start",  

	"keywords": [
	"CFDI",
	"XML",
	"PDF",
	"tutorial"
	],
	"author": "Julio Cesar Leyva Rodriguez",
	"license": "CC0-1.0",
	"devDependencies": {
	"electron": "^21.2.3",
	"electron-builder": "^22.14.13",
	"electron-packager": "^17.1.1"
	},
	"dependencies": {
	"modclean": "^3.0.0-beta.1"
	}
	}

en main.js lo dejamos haci lo que hara es cargar la url y levantar el servicio de php

	// Modules to control application life and create native browser window

	const {app, BrowserWindow} = require('electron')

	const path = require('path')

	const exec = require('child_process').exec;

	  
	  

	function execute(command, callback) {

	exec(command, (error, stdout, stderr) => {

	callback(stdout);

	});

	};

	  
	  

	// call the function

	execute('Ejecutar.bat', (output) => {

	console.log(output);

	});

	  

	function createWindow () {

	// Create the browser window.

	const mainWindow = new BrowserWindow({

	width: 800,

	height: 600,

	webPreferences: {

	preload: path.join(__dirname, 'preload.js')

	}

	})

	  

	// and load the index.html of the app.

	mainWindow.setMenu(null)

	mainWindow.loadURL('http://localhost:8097')

	  

	// Open the DevTools.

	// mainWindow.webContents.openDevTools()

	}

	  

	// This method will be called when Electron has finished

	// initialization and is ready to create browser windows.

	// Some APIs can only be used after this event occurs.

	app.whenReady().then(() => {

	createWindow()

	  

	app.on('activate', function () {

	// On macOS it's common to re-create a window in the app when the

	// dock icon is clicked and there are no other windows open.

	if (BrowserWindow.getAllWindows().length === 0) createWindow()

	})

	})

	  

	// Quit when all windows are closed, except on macOS. There, it's common

	// for applications and their menu bar to stay active until the user quits

	// explicitly with Cmd + Q.

	app.on('window-all-closed', function () {

	if (process.platform !== 'darwin') app.quit()

	})

	  

	// In this file you can include the rest of your app's specific main process

	// code. You can also put them in separate files and require them here.

ahora posicionados en la carpeta \electron-quick-start> corremos el siguiente comando

npm install

Después creamos el paquete-ejecutable con el siguiente comando

electron-packager . -platform=win32 -arch=x64 ConversorXMLPDF

y nos genera los archivos necesarios
image

Creamos una carpeta en C: llamada aplicación o como ustedes quieran llamarle y copiamos el contenido, la carpeta del proyecto del codeigniter y los archivos ejecutable de PHP con los que trabajan, pueden copiar los del xampp y con el que debugean a través de netbeans
quedaría de la siguiente forma

image

ConvertidorXMLPDF seria el proyecto en codeigniter, php8 son los binarios necesarios para ejecutar código php, este lo pueden extraer de xampp y lo demas son los archivos de electronJS

Ahora en el archivo de configuración de código igniter en config/app.php en la base URL la dejamos asi

public $baseURL = '[http://localhost:8097/](http://localhost:8097/)';

El archivo Ejecutar.bat es el que va iniciar todo el codeigniter y dentro de el va el siguiente codigo

@echo off

php8\php.exe convertidorXMLPDF/spark serve --port 8097

El archivo Ejecutar.bat se ejecuta automáticamente al abrir el ejecutable

Y listo ahora solo queda hacer el instalador pero lo dejamos para otro manual.

Crear un Conversor de Facturas XML Mexicanas a PDF en CodeIgniter4

En este pequeño tutorial vamos a mostrar como crear rápidamente un conversor XML a PDF de las facturas electrónicas Mexicanas
Requisitos

  1. Tener instalado la versión mas reciente de Composer
  2. Conocimiento básico de PHP y Programación
  3. Ganas de aprender

Paso uno creamos el proyecto en CodeIgniter 4

composer create-project codeigniter4/appstarter convertidorXMLPDF

Actualizamos

composer update

Instalamos de composer el paquete que convierte el xml PDF

composer require phpcfdi/cfditopdf

creamos el archivo FileUpload.php en controladores

<?php 
namespace App\Controllers;
// use App\Models\FormModel;
use CodeIgniter\Controller;
class FileUpload extends Controller
{
    public function index() 
    {
        return view('home');
    }
    function upload() { 
        helper(['form', 'url','filesystem']);



 
            $xml = $this->request->getFile('file');
           /* $img->move(WRITEPATH . 'uploads');
    
            $data = [
               'name' =>  $img->getName(),
               'type'  => $img->getClientMimeType()
            ];
    
            $save = $db->insert($data);
            print_r('File has successfully uploaded');     */


         //  echo $_FILES['file']['tmp_name'];
            $string = file_get_contents($_FILES['file']['tmp_name']);

         
            // clean cfdi
            $xml = \PhpCfdi\CfdiCleaner\Cleaner::staticClean($string);

            
         
            // create the main node structure
            $comprobante = \CfdiUtils\Nodes\XmlNodeUtils::nodeFromXmlString($xml);

            // create the CfdiData object, it contains all the required information
            $cfdiData = (new \PhpCfdi\CfdiToPdf\CfdiDataBuilder())
                ->build($comprobante);

            // create the converter
            $converter = new \PhpCfdi\CfdiToPdf\Converter(
                new \PhpCfdi\CfdiToPdf\Builders\Html2PdfBuilder()
            );

            // create the invoice as output.pdf
            $converter->createPdfAs($cfdiData,  'output.pdf');
            
                $filename = WRITEPATH . 'uploads\output.pdf';
                
                echo '
                <script type="text/javascript">
                    window.open("/output.pdf" , "_blank");
                  </script>';
                
             
               return view('welcome_message');
                  
                
        }
     
    
}

*Agregamos el formulario en las vistas en este caso al archivo welcome_message.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Conversor CFDI!</title>
        <meta name="description" content="Pequeño y poderoso conversor de CFDI XML a PDF hecho en CodeIgnter">
        <meta name="keywords" content="CFDI, CFDI 4.0, CFDI 3.3, Representación Impresa, CodeIgniter, Factura Electrónica"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="shortcut icon" type="image/png" href="/favicon.ico"/>

        <!-- STYLES -->

        <style {csp-style-nonce}>
            * {
                transition: background-color 300ms ease, color 300ms ease;
            }
            *:focus {
                background-color: rgba(221, 72, 20, .2);
                outline: none;
            }
            html, body {
                color: rgba(33, 37, 41, 1);
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
                font-size: 16px;
                margin: 0;
                padding: 0;
                -webkit-font-smoothing: antialiased;
                -moz-osx-font-smoothing: grayscale;
                text-rendering: optimizeLegibility;
            }
            header {
                background-color: rgba(247, 248, 249, 1);
                padding: .4rem 0 0;
            }
            .menu {
                padding: .4rem 2rem;
            }
            header ul {
                border-bottom: 1px solid rgba(242, 242, 242, 1);
                list-style-type: none;
                margin: 0;
                overflow: hidden;
                padding: 0;
                text-align: right;
            }
            header li {
                display: inline-block;
            }
            header li a {
                border-radius: 5px;
                color: rgba(0, 0, 0, .5);
                display: block;
                height: 44px;
                text-decoration: none;
            }
            header li.menu-item a {
                border-radius: 5px;
                margin: 5px 0;
                height: 38px;
                line-height: 36px;
                padding: .4rem .65rem;
                text-align: center;
            }
            header li.menu-item a:hover,
            header li.menu-item a:focus {
                background-color: rgba(221, 72, 20, .2);
                color: rgba(221, 72, 20, 1);
            }
            header .logo {
                float: left;
                height: 44px;
                padding: .4rem .5rem;
            }
            header .menu-toggle {
                display: none;
                float: right;
                font-size: 2rem;
                font-weight: bold;
            }
            header .menu-toggle button {
                background-color: rgba(221, 72, 20, .6);
                border: none;
                border-radius: 3px;
                color: rgba(255, 255, 255, 1);
                cursor: pointer;
                font: inherit;
                font-size: 1.3rem;
                height: 36px;
                padding: 0;
                margin: 11px 0;
                overflow: visible;
                width: 40px;
            }
            header .menu-toggle button:hover,
            header .menu-toggle button:focus {
                background-color: rgba(221, 72, 20, .8);
                color: rgba(255, 255, 255, .8);
            }
            header .heroe {
                margin: 0 auto;
                max-width: 1100px;
                padding: 1rem 1.75rem 1.75rem 1.75rem;
            }
            header .heroe h1 {
                font-size: 2.5rem;
                font-weight: 500;
            }
            header .heroe h2 {
                font-size: 1.5rem;
                font-weight: 300;
            }
            section {
                margin: 0 auto;
                max-width: 1100px;
                padding: 2.5rem 1.75rem 3.5rem 1.75rem;
            }
            section h1 {
                margin-bottom: 2.5rem;
            }
            section h2 {
                font-size: 120%;
                line-height: 2.5rem;
                padding-top: 1.5rem;
            }
            section pre {
                background-color: rgba(247, 248, 249, 1);
                border: 1px solid rgba(242, 242, 242, 1);
                display: block;
                font-size: .9rem;
                margin: 2rem 0;
                padding: 1rem 1.5rem;
                white-space: pre-wrap;
                word-break: break-all;
            }
            section code {
                display: block;
            }
            section a {
                color: rgba(221, 72, 20, 1);
            }
            section svg {
                margin-bottom: -5px;
                margin-right: 5px;
                width: 25px;
            }
            .further {
                background-color: rgba(247, 248, 249, 1);
                border-bottom: 1px solid rgba(242, 242, 242, 1);
                border-top: 1px solid rgba(242, 242, 242, 1);
            }
            .further h2:first-of-type {
                padding-top: 0;
            }
            footer {
                background-color: rgba(221, 72, 20, .8);
                text-align: center;
            }
            footer .environment {
                color: rgba(255, 255, 255, 1);
                padding: 2rem 1.75rem;
            }
            footer .copyrights {
                background-color: rgba(62, 62, 62, 1);
                color: rgba(200, 200, 200, 1);
                padding: .25rem 1.75rem;
            }
            @media (max-width: 629px) {
                header ul {
                    padding: 0;
                }
                header .menu-toggle {
                    padding: 0 1rem;
                }
                header .menu-item {
                    background-color: rgba(244, 245, 246, 1);
                    border-top: 1px solid rgba(242, 242, 242, 1);
                    margin: 0 15px;
                    width: calc(100% - 30px);
                }
                header .menu-toggle {
                    display: block;
                }
                header .hidden {
                    display: none;
                }
                header li.menu-item a {
                    background-color: rgba(221, 72, 20, .1);
                }
                header li.menu-item a:hover,
                header li.menu-item a:focus {
                    background-color: rgba(221, 72, 20, .7);
                    color: rgba(255, 255, 255, .8);
                }
            }
        </style>
    </head>
    <body>

        <!-- HEADER: MENU + HEROE SECTION -->
        <header>

            <div class="menu">
                <ul>
                    <li class="logo">
                        <a href="https://cesarsystems.com.mx/" target="_blank">
                            <img src="<?php echo base_url();?>/logo.png"
                                 aria-label="Visita mi pagina oficial para mas programas y utilidades!"/></img>
                        </a>
                    </li>
                    <li class="menu-toggle">
                        <button onclick="toggleMenu();">&#9776;</button>
                    </li>
                    <li class="menu-item hidden"><a href="#">Inicio</a></li>
                    <li class="menu-item hidden"><a href="https://cesarsystems.com.mx/" target="_blank">Descargas</a>
                    </li>
                    <li class="menu-item hidden"><a href="https://www.youtube.com/c/rasec555" target="_blank">Comunidad</a></li>
                    <li class="menu-item hidden"><a
                            href="https://patreon.com/user?u=74078772&utm_medium=clipboard_copy&utm_source=copyLink&utm_campaign=creatorshare_creator" target="_blank">Patrocinar</a>
                    </li>
                </ul>
            </div>

            <div class="heroe">

                <h1>Bienvenido a Conversor XML A PDF V2</h1>

                <h2>Un simple software para convertir los CFDI XML a PDF</h2>

            </div>

        </header>

        <!-- CONTENT -->

        <section>

            <h1>Acerca de este programa</h1>

            <p>Este programa toma los archivos XML de la factura 3.3 o 4.0 para convertirlos a una representación generica impresa de un Comprobante Fiscal Digital</p>

            <p>Para convertir el XML a PDF puede arrastrar el archivo XML en el Boton llamado "Seleccionar archivo" </p>

            <p>En caso de que no salga el PDF asegurate de no tener bloqueado el popup o desbloquealo para esta pagina ya que el pdf saldra en el popup" </p>



            <form method="post" action="<?php echo base_url('FileUpload/upload'); ?>" enctype="multipart/form-data">
                <div class="form-group">
                    <label>Seleccione el archivo XML </label>
                    <input type="file" name="file" id="file"  accept=".xml" class="form-control">
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-danger">Generar PDF</button>
                </div>
            </form>

        </section>

        <div class="further">

            <section>

                <h1>¡Ir por más!</h1>

                <h2>
                    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><rect x='32' y='96' width='64' height='368' rx='16' ry='16' style='fill:none;stroke:#000;stroke-linejoin:round;stroke-width:32px'/><line x1='112' y1='224' x2='240' y2='224' style='fill:none;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/><line x1='112' y1='400' x2='240' y2='400' style='fill:none;stroke:#000;stroke-linecap:round;stroke-linejoin:round;stroke-width:32px'/><rect x='112' y='160' width='128' height='304' rx='16' ry='16' style='fill:none;stroke:#000;stroke-linejoin:round;stroke-width:32px'/><rect x='256' y='48' width='96' height='416' rx='16' ry='16' style='fill:none;stroke:#000;stroke-linejoin:round;stroke-width:32px'/><path d='M422.46,96.11l-40.4,4.25c-11.12,1.17-19.18,11.57-17.93,23.1l34.92,321.59c1.26,11.53,11.37,20,22.49,18.84l40.4-4.25c11.12-1.17,19.18-11.57,17.93-23.1L445,115C443.69,103.42,433.58,94.94,422.46,96.11Z' style='fill:none;stroke:#000;stroke-linejoin:round;stroke-width:32px'/></svg>
                    Descargas y tutoriales
                </h2>

                <p>Puedes encontrar mas aplicativos, manuales y tutoriales en la siguiente pagina <a href="https://cesarsystems.com.mx/"
                                                target="_blank">Pagina Principal</a> !</p>

                <h2>
                    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path d='M431,320.6c-1-3.6,1.2-8.6,3.3-12.2a33.68,33.68,0,0,1,2.1-3.1A162,162,0,0,0,464,215c.3-92.2-77.5-167-173.7-167C206.4,48,136.4,105.1,120,180.9a160.7,160.7,0,0,0-3.7,34.2c0,92.3,74.8,169.1,171,169.1,15.3,0,35.9-4.6,47.2-7.7s22.5-7.2,25.4-8.3a26.44,26.44,0,0,1,9.3-1.7,26,26,0,0,1,10.1,2L436,388.6a13.52,13.52,0,0,0,3.9,1,8,8,0,0,0,8-8,12.85,12.85,0,0,0-.5-2.7Z' style='fill:none;stroke:#000;stroke-linecap:round;stroke-miterlimit:10;stroke-width:32px'/><path d='M66.46,232a146.23,146.23,0,0,0,6.39,152.67c2.31,3.49,3.61,6.19,3.21,8s-11.93,61.87-11.93,61.87a8,8,0,0,0,2.71,7.68A8.17,8.17,0,0,0,72,464a7.26,7.26,0,0,0,2.91-.6l56.21-22a15.7,15.7,0,0,1,12,.2c18.94,7.38,39.88,12,60.83,12A159.21,159.21,0,0,0,284,432.11' style='fill:none;stroke:#000;stroke-linecap:round;stroke-miterlimit:10;stroke-width:32px'/></svg>
                    Grupos
                </h2>

                <p>Puede seguirnos en los siguientes grupos y redes sociales como <a href="https://www.youtube.com/c/rasec555"
                                      target="_blank">Canal de youtube </a>, 
                                      
                                      <a href="https://t.me/CesarSystems"
                                      target="_blank">Canal de Telegram</a> ,
                                      
                                      <a href="https://twitter.com/JulioLeyvaR"
                                      target="_blank">Twitter</a> ,
                                      
                                       <a href="https://odysee.com/@JulioCesarLeyvaRodriguez:9"
                                      target="_blank">Odysee</a> y
                                      
                                      <a href="https://www.facebook.com/rasec555/"
                                      target="_blank">Facebook</a> 
                
                
                </p>

                <h2>
                    <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><line x1='176' y1='48' x2='336' y2='48' style='fill:none;stroke:#000;stroke-linecap:round;stroke-miterlimit:10;stroke-width:32px'/><line x1='118' y1='304' x2='394' y2='304' style='fill:none;stroke:#000;stroke-linecap:round;stroke-miterlimit:10;stroke-width:32px'/><path d='M208,48v93.48a64.09,64.09,0,0,1-9.88,34.18L73.21,373.49C48.4,412.78,76.63,464,123.08,464H388.92c46.45,0,74.68-51.22,49.87-90.51L313.87,175.66A64.09,64.09,0,0,1,304,141.48V48' style='fill:none;stroke:#000;stroke-linecap:round;stroke-miterlimit:10;stroke-width:32px'/></svg>
                    Patrocinar
                </h2>

                <p>Puedes apoyar nuestros proyectos en Patreon y obtendras acceso exclusivo a los fuentes mas recientes
                    <a href="https://patreon.com/user?u=74078772&utm_medium=clipboard_copy&utm_source=copyLink&utm_campaign=creatorshare_creator" target="_blank">
                        Unete</a> </p>

            </section>

        </div>

        <!-- FOOTER: DEBUG INFO + COPYRIGHTS -->

        <footer>
            <div class="environment">

                <p>Tiempo de Renderizado {elapsed_time} seconds</p>

            

            </div>

            <div class="copyrights">

                <p>&copy; <?= date('Y') ?> Conversor XML a PDF es un proyecto de código abierto lanzado con la licencia MIT
                    open source licence.</p>

            </div>

        </footer>

        <!-- SCRIPTS -->

        <script>
            function toggleMenu() {
                var menuItems = document.getElementsByClassName('menu-item');
                for (var i = 0; i < menuItems.length; i++) {
                    var menuItem = menuItems[i];
                    menuItem.classList.toggle("hidden");
                }
            }
        </script>

        <!-- -->

    </body>
</html>

Y por último agregamos esto en las rutas

$routes->get('/', 'FileUpload::index');
$routes->match(['get', 'post'], 'FileUpload/upload', 'FileUpload::upload');

y listo pueden ver un ejemplo de como quedo en el siguiente enlace https://xml2pdf.cesarsystems.com.mx/

Novedades MX Linux 21 WILDFLOWER

Ha salido hace ya hace un poco de tiempo la versión 21 de MX LINUX, la distribución que se mantiene en el primer lugar en la top 100 de la WEB distrowatch así que vamos a dedicarle un post, sobre todo especificando la versión que viene con el entorno de escritorio XFCE

Para resumir rápidamente les dejo las novedades que tiene esta versión

Como publicar proyecto de gambas3 en la granja de software

Suponiendo que ya esta listo el programa lo que sigue puede ser lo siguiente
1. Crear un simple Ejecutable
2. Crear un paquete de instalación para instalarlo en cualquier distribución de Linux a través de un empaquetado .deb
3. Publicarlo en la granja de software de Gambas3

Lo que haremos es publicarlo en la granja de software

Primero le asignamos un icono al proyecto en las propiedades del proyecto

Aprovechamos para escribir la descripción del proyecto y los autores

Ahora nos vamos al menú Proyecto -> Publicar

Le rellenamos mas datos en caso de ser necesario
Elegimos las etiquetas
Elegimos una captura del programa, esto de mostrara cuando alguien quiera descargar nuestro programa
Elegimos las dependencias
Elegimos si publicarlo con nuestro usuario, aunque se puede publicar bajo el anonimato sin crear usuario en gambasfarm.org

Finalmente le damos Publicar y mostrara el siguiente mensaje comunicándonos de que el proyecto se ha publicado correctamente
Si nos vamos a la granja de software ya estará publicado nuestro proyecto

Como guardar archivos en disco duro con GAMBAS3 File.Save

Ya tenemos las funciones para crear automáticamente los códigos del Modelo/Vista/Controlador para PHP ahora lo que sigue es crear los archivos en el directorio del directorio del proyecto en PHP

Para guardar archivo en Gambas3 usaremos la función File.Save(“ruta donde se va a guardar”,”contenido del archivo”)

Pasos

Le damos doble click al botton para generar el evento _Click
Quedara de la siguiente forma

Insertamos en ese evento el siguiente código

  Dim strModel1 As String
  Dim strControlador As String
  Dim strVista As String 
  
  ' GUARDAR CONFIGURACION

  
  Settings["ruta"] = ruta.SelectedPath
  Settings["tabla"] = txtTabla.Text
  
  ' CREA ARCHIVO DEL MODELO
  strModel1 = creadorModelo.creaModelo()
   
  File.Save(ruta.SelectedPath & "/" & "modelos/" & txtTabla.Text & ".modelo.php", strModel1)
  
  ' CREA ARCHIVO DEL CONTROLADOR
  strControlador = creadorControlador.creaControlador()
  
  File.Save(ruta.SelectedPath & "/" & "controladores/" & txtTabla.Text & ".controlador.php", strControlador)
   
   
  ' CREA ARCHIVO VISTA 
  strVista = creadorVista.creaVista()
  
  File.Save(ruta.SelectedPath & "/" & "vistas/modulos/" & txtTabla.Text & ".php", strVista)
  
  ' MANDAMOS MENSAJE DE QUE TODO SE HA GUARDADO CORRECTAMENTE
  Message.Info("Guardado Correctamente")
Se observa como se usan las funciones para crear el código, por ejemplo, para crear el modelo se usa creadorModelo.creaModelo() y guarda todo el texto/código generado en la variable strModel1

Luego guarda con File.Save en la ruta que seleccionamos con el control llamado “ruta” el texto que esta en strModel

Esta misma lógica se usa para el controlador y la vista

En la siguiente publicación veremos como asignarle un icono al proyecto

Función para crear automáticamente el código de la vista en base a una tabla en MySQL

Ahora solo queda hacer la función para generar automáticamente el código HTML/PHP para la vista del catalogo en base a la nueva tabla.

La lógica es igual solo que es otro texto

Creamos el modulo creadorVista en la carpeta modulos

Insertamos el siguiente codigo

' Gambas module file

Public Function creaVista() As String
  
  Dim strVista As String
  
  Dim conexion As New Connection
  Dim strDatos As String
  


  With conexion
    .Type = "mysql"
    .Port = "3306"
    .Host = Settings["servidor"]
    .User = Settings["usuario"]
    .Password = Settings["password"]
    .Name = Settings["baseDeDatos"]
    .Open()
    End With
    
    Dim $result As Result
    Dim $resultClases As Result
    Dim strLLavePrimaria As String
    
   $result = conexion.Exec("SHOW KEYS FROM  " & FMain.txtTabla.Text & " WHERE Key_name = 'PRIMARY'")
   strLLavePrimaria = $result["Column_name"]
   
   
   conexion.Exec("delete from clases where clase= 'controladores/" & FMain.txtTabla.Text & ".controlador.php'")
   conexion.Exec("delete from clases where clase= 'modelos/" & FMain.txtTabla.Text & ".modelo.php'")
   conexion.Exec("insert into clases(clase) values('controladores/" & FMain.txtTabla.Text & ".controlador.php')")
   conexion.Exec("insert into clases(clase) values( 'modelos/" & FMain.txtTabla.Text & ".modelo.php')")
  
  
   $result = conexion.Exec("describe " & FMain.txtTabla.Text)
  $result = conexion.Exec("describe " & FMain.txtTabla.Text)
  
  
Dim contador As Integer
Dim strEncabezadosTabla As String
Dim strCampos As String
Dim strControlesNuevos As String
Dim strControlesEditar As String
Dim strEditarJS As String
Dim strBloquear As String
Dim strEditarTraeDatos As String

contador = 0
strEncabezadosTabla = ""
strCampos = ""
strControlesNuevos = ""
strEditarJS = ""

While $result.Length > contador
  
  strEncabezadosTabla &= "<th>" & utilerias.strPrimeraMayuscula($result["Field"]) & "</th>" & gb.CrLf 
  
  strCampos &= "<td>'.$value[\"" & $result["Field"] & "\"].'</td>" & gb.CrLf 
  
  If contador > 0

  strControlesNuevos &= "" & "            <!-- ENTRADA PARA " & UCase($result["Field"]) & " --> " & gb.CrLf
  strControlesNuevos &= "" & " " & gb.CrLf
  strControlesNuevos &= "" & "            <div class=\"form-group\"> " & gb.CrLf
  strControlesNuevos &= "" & " " & gb.CrLf
  strControlesNuevos &= "" & "              <div class=\"input-group\"> " & gb.CrLf
  strControlesNuevos &= "" & " " & gb.CrLf
  strControlesNuevos &= "" & "                <span class=\"input-group-addon\">" & utilerias.strPrimeraMayuscula($result["Field"]) & ": </span>  " & gb.CrLf
  strControlesNuevos &= "" & " " & gb.CrLf
  strControlesNuevos &= "" & "                <input type=\"text\" class=\"form-control input-lg\" name=\"nuevo" & utilerias.strPrimeraMayuscula($result["Field"]) & "\" placeholder=\"Ingresar " & utilerias.strPrimeraMayuscula($result["Field"]) & "\" required> " & gb.CrLf
  strControlesNuevos &= "" & " " & gb.CrLf
  strControlesNuevos &= "" & "              </div> " & gb.CrLf
  strControlesNuevos &= "" & " " & gb.CrLf
  strControlesNuevos &= "" & "            </div> " & gb.CrLf
  
  strEditarJS &= "" & "            $(\"#editarDescripcion\").val(respuesta[\"descripcion\"]);" & gb.CrLf

  End If
  
  
  If $result["Key"] == "PRI" 
    strBloquear = "readonly"
    Else
    strBloquear = ""
   End If
    
  
  
  strControlesEditar &= "" & "            <!-- ENTRADA PARA " & UCase($result["Field"]) & " --> " & gb.CrLf
  strControlesEditar &= "" & " " & gb.CrLf
  strControlesEditar &= "" & "            <div class=\"form-group\"> " & gb.CrLf
  strControlesEditar &= "" & " " & gb.CrLf
  strControlesEditar &= "" & "              <div class=\"input-group\"> " & gb.CrLf
  strControlesEditar &= "" & " " & gb.CrLf
  strControlesEditar &= "" & "                <span class=\"input-group-addon\">" & utilerias.strPrimeraMayuscula($result["Field"]) & ": </span>  " & gb.CrLf
  strControlesEditar &= "" & " " & gb.CrLf
  strControlesEditar &= "" & "                <input " & strBloquear & "  type=\"text\" class=\"form-control input-lg\" id=\"editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\" name=\"editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\" placeholder=\"Ingresar " & utilerias.strPrimeraMayuscula($result["Field"]) & "\" required> " & gb.CrLf
  strControlesEditar &= "" & " " & gb.CrLf
  strControlesEditar &= "" & "              </div> " & gb.CrLf
  strControlesEditar &= "" & " " & gb.CrLf
  strControlesEditar &= "" & "            </div> " & gb.CrLf
  
  strEditarTraeDatos &= "" & "            $(\"#editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\").val(respuesta[\"" & $result["Field"] & "\"]); " & gb.CrLf 

  $result.MoveNext
  contador = contador + 1


Wend
  strControlesEditar &= "" & " <input type=\"hidden\" id=\"editar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "\"  name = \"editar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "\" > " & gb.CrLf 
  strEncabezadosTabla &= "<th>Acciones</th>" 
  strCampos &= "<td> " & gb.CrLf
  strCampos &= "<div class = \"btn-group\"> " & gb.CrLf
  
  
 
   strCampos &= "                    <button class= \"btn btn-warning btnEditar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\" id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & " = \"'.$value[\"id\"].'\" data-toggle = \"modal\" data-target = \"#modalEditar" & Trim(utilerias.strPrimeraMayuscula(FMain.txtTabla.Text)) & "\"> <i class = \"fa fa-pencil\"> </i> </button> " & gb.CrLf
 
strCampos &= "<button class = \"btn btn-danger btnEliminar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\" id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "= \"'.$value[\"id\"].'\"><i class= \"fa fa-times\"></i></button>" & gb.CrLf
 
strCampos &= "</div>" & gb.CrLf
 
strCampos &= "</td> " & gb.CrLf
    
  strVista &= "" & "<?php" & gb.CrLf
  strVista &= "" & gb.CrLf
  strVista &= "" & "if(\"off\" == \"offf\"){" & gb.CrLf
  strVista &= "" & gb.CrLf
  strVista &= "" & "  echo '<script>" & gb.CrLf
  strVista &= "" & gb.CrLf
  strVista &= "" & "    window.location = \"inicio\"; " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  </script>'; " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  return; " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "} " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "?> " & gb.CrLf
  strVista &= "" & "<div class=\"content-wrapper\">" & gb.CrLf 
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  <section class=\"content-header\">" & gb.CrLf 
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    <h1> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      Administrar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " ')); ?> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    </h1> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    <ol class=\"breadcrumb\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      <li><a href=\"inicio\"><i class=\"fa fa-dashboard\"></i> Inicio</a></li> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      <li class=\"active\">Administrar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', '" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " ')); ?></li> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    </ol> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  </section> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  <section class=\"content\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    <div class=\"box\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      <div class=\"box-header with-border\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <button class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#modalAgregar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          Agregar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', '" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " ')); ?> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      <div class=\"box-body\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "       <table class=\"table table-bordered table-striped dt-responsive tablas\" width=\"100%\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <thead> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "         <tr> " & gb.CrLf
  strVista &= "" & " " & strEncabezadosTabla
  strVista &= "" & "         </tr>  " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </thead> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <tbody> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <?php " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        $item = null; " & gb.CrLf
  strVista &= "" & "        $valor = null; " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        $" & FMain.txtTabla.Text & "= Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "::ctrMostrar($item, $valor); " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "       foreach ($" & FMain.txtTabla.Text & " as $key => $value){ " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  
  
  
  strVista &= "" & "          echo ' <tr> " & gb.CrLf

  strVista &= "" & strCampos & gb.CrLf

  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "                </tr>'; " & gb.CrLf
  strVista &= "" & "        } " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        ?>  " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </tbody> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "       </table> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  </section> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "</div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "<!--===================================== " & gb.CrLf
  strVista &= "" & "MODAL <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (FMain.txtTabla.Text) & " ')); ?> " & gb.CrLf
  strVista &= "" & " ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "<div id=\"modalAgregar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "\" class=\"modal fade\" role=\"dialog\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  <div class=\"modal-dialog\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    <div class=\"modal-content\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      <form role=\"form\" method=\"post\" enctype=\"multipart/form-data\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <!--===================================== " & gb.CrLf
  strVista &= "" & "        CABEZA DEL MODAL " & gb.CrLf
  strVista &= "" & "        ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <div class=\"modal-header\" style=\"background:#3c8dbc; color:white\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <h4 class=\"modal-title\">Agregar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (FMain.txtTabla.Text) & " ')); ?> </h4> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf

  strVista &= "" & "        </div> " & gb.CrLf
 
  strVista &= "" & "        <!--===================================== " & gb.CrLf
  strVista &= "" & "        CUERPO DEL MODAL " & gb.CrLf
  strVista &= "" & "        ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <div class=\"modal-body\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <div class=\"box-body\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  'strVista &= "" & "            <!-- ENTRADA PARA DESCRIPCION --> " & gb.CrLf
  
    strVista &= "" & " " & strControlesNuevos & gb.CrLf
  
  
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <!--===================================== " & gb.CrLf
  strVista &= "" & "        PIE DEL MODAL " & gb.CrLf
  strVista &= "" & "        ====================================== --> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <div class=\"modal-footer\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <button type=\"button\" class=\"btn btn-default pull-left\" data-dismiss=\"modal\">Salir</button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <button type=\"submit\" class=\"btn btn-primary\">Guardar</button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <?php " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "           $crear = new Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "(); " & gb.CrLf
  strVista &= "" & "           $crear ->ctrIngresar(); " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        ?> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      </form> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "</div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "<!--===================================== " & gb.CrLf
  strVista &= "" & "MODAL EDITAR USUARIO " & gb.CrLf
  strVista &= "" & " ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "<div id=\"modalEditar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\" class=\"modal fade\" role=\"dialog\">" & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  <div class=\"modal-dialog\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    <div class=\"modal-content\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      <form role=\"form\" method=\"post\" enctype=\"multipart/form-data\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <!--===================================== " & gb.CrLf
  strVista &= "" & "        CABEZA DEL MODAL " & gb.CrLf
  strVista &= "" & "        ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <div class=\"modal-header\" style=\"background:#3c8dbc; color:white\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <button type=\"button\" class=\"close\" data-dismiss=\"modal\">&times;</button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <h4 class=\"modal-title\">Agregar <?php echo  mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (FMain.txtTabla.Text) & " ')); ?> </h4> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <!--===================================== " & gb.CrLf
  strVista &= "" & "        CUERPO DEL MODAL " & gb.CrLf
  strVista &= "" & "        ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <div class=\"modal-body\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <div class=\"box-body\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "            <!-- ENTRADA PARA DESCRIPCION --> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & strControlesEditar
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <!--===================================== " & gb.CrLf
  strVista &= "" & "        PIE DEL MODAL " & gb.CrLf
  strVista &= "" & "        ======================================--> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        <div class=\"modal-footer\"> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <button type=\"button\" class=\"btn btn-default pull-left\" data-dismiss=\"modal\">Salir</button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "          <button type=\"submit\" class=\"btn btn-primary\">Modificar</button> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "     <?php " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "           $editar = new Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "(); " & gb.CrLf
  strVista &= "" & "           $editar ->ctrEditar(); " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "        ?>  " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "      </form> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "    </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "  </div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "</div> " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "<?php " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "   $borrar = new Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "(); " & gb.CrLf
  strVista &= "" & "   $borrar ->ctrBorrar(); " & gb.CrLf
  strVista &= "" & " " & gb.CrLf
  strVista &= "" & "?>  " & gb.CrLf
  
  'JAVASCRIPT FUNCIONES
  strVista &= "" & "<script type=\"text/javascript\">" & gb.CrLf
  
    'ELIMINAR
 
  
strVista &= "" & "/*= == == == == == == == == == == == == == == == == == == == == == ==" & gb.CrLf
strVista &= "" & " ELIMINAR " & UCase(FMain.txtTabla.Text) & gb.CrLf
strVista &= "" & " == == == == == == == == == == == == == == == == == == == == == == = */" & gb.CrLf
strVista &= "" & "$(\".tablas\").on(\"click\", \".btnEliminar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", function() {" & gb.CrLf 

strVista &= "" & "    var id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " = $(this).attr(\"id" & FMain.txtTabla.Text & "\");" & gb.CrLf

strVista &= "" & "    swal( {" & gb.CrLf
strVista &= "" & "        title: '¿Está seguro de borrar?'," & gb.CrLf
strVista &= "" & "        text: \"¡Si no lo está puede cancelar la accíón!\"," & gb.CrLf
strVista &= "" & "        type: 'warning'," & gb.CrLf
strVista &= "" & "        showCancelButton: true," & gb.CrLf
strVista &= "" & "        confirmButtonColor: '#3085d6'," & gb.CrLf
strVista &= "" & "        cancelButtonColor: '#d33'," & gb.CrLf
strVista &= "" & "        cancelButtonText: 'Cancelar'," & gb.CrLf
strVista &= "" & "       confirmButtonText: 'Si, borrar!'" & gb.CrLf
strVista &= "" & "    }).then(function(result) {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "        if (result.value) {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "            window.location = \"index.php?ruta=" & (FMain.txtTabla.Text) & "&id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "=\"+id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "+\"&borrar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "=borrar\";" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "        }" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "    })" & gb.CrLf

strVista &= "" & "})" & gb.CrLf


'editar

strVista &= "" & "/* = == == == == == == == == == == == == == == == == == == == == == ==" & gb.CrLf
strVista &= "" & " EDITAR " & gb.CrLf
strVista &= "" & " == == == == == == == == == == == == == == == == == == == == == == = */" & gb.CrLf
strVista &= "" & "$(\".tablas\").on(\"click\", \".btnEditar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", function() {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "    var id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " = $(this).attr(\"id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\");" & gb.CrLf
strVista &= "" & "  console.log(id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & ");"
strVista &= "" & "" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "    var datos = new FormData();" & gb.CrLf
strVista &= "" & "    datos.append(\"id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "); " & gb.CrLf 
strVista &= "" & "    datos.append(\"buscar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", \"buscar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\");" & gb.CrLf
strVista &= "" & "   " & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "    $.ajax( {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "        url:\"controladores/" & FMain.txtTabla.text & ".controlador.php\"," & gb.CrLf
strVista &= "" & "        method:\"POST\"," & gb.CrLf
strVista &= "" & "        data: datos," & gb.CrLf
strVista &= "" & "        cache: false," & gb.CrLf
strVista &= "" & "        contentType: false," & gb.CrLf
strVista &= "" & "        processData: false," & gb.CrLf
strVista &= "" & "       dataType:\"json\"," & gb.CrLf
strVista &= "" & "       success: function(respuesta) {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & strEditarTraeDatos & gb.CrLf
strVista &= "" & "            " & gb.CrLf
strVista &= "" & "        }" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "    });" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "})" & gb.CrLf

  
  strVista &= "" & "</script>" & gb.CrLf
  Return strVista

End

En la siguiente publicación veremos como generar los archivos modelos/vista/Controlador al darle click al botón Crear Catalogo

Crear función en GAMBAS3 para crear el código para el archivo controlador en php8

Ya hemos visto como crear el archivo modelo en base a la nueva tabla

Para crear el contenido del archivo controlador la lógica es igual

Función en GAMBAS3 para convertir la primera letra de una cadena a Mayúscula

Vimos en la publicación anterior que usamos una función para convertir la primera letra de un texto a mayúsculas por lo tanto vamos a explicar como funciona este código

Es decir si ponemos strPrimeraMayuscula(“prueba”) nos va a devolver “Prueba“, con la P Mayúscula

Primero creamos otro modulo llamado utilitarias, este nos servirá para meter funciones generales

Vemos que se usa la funcion Mid$ que en el primer caso mandamos los parametros 1,1 lo cual solo tomara en cuenta la primer letra del texto y a eso lo metemos a la funcion UCase que lo convierte a mayuscula, luego concatena con Mid$ sin usar UCase pero empezando desde la segunda posición
' Gambas module file

Public Function strPrimeraMayuscula(strCadena As String) As String
  
  Return UCase(Mid$(strCadena, 1, 1)) & Mid$(strCadena, 2, 100) 

End

En la siguiente publicación veremos como generar el texto que va dentro del archivo controlador

Conexión a la base de datos MySQL en GAMBAS

Es necesario podernos conectar a la base de datos del punto de venta para poder leer los campos y en base a esto crear los archivos del catalogo de la tabla nueva

Los pasos son los siguientes

En caso de tener dificultades para encontrar el componente nos podemos ayudar del buscador de arriba
Creamos el modulo creadorModelo en la carpeta módulos, este archivo contendrá la función con la cual se conectara a la base de datos y leerá la la tabla y con esos datos creara el archivo modelo.php

Ahora pegamos el siguiente código

' Gambas module file

Public Function creaModelo() As String

Dim strModelo As String
Dim conexion As New Connection

  ' AQUI ABRIMOS LA CONEXION
  With conexion
    .Type = "mysql"
    .Port = "3306"
    .Host = Settings["servidor"]
    .User = Settings["usuario"]
    .Password = Settings["password"]
    .Name = Settings["baseDeDatos"]
    .Open()
  End With
  
  Dim $result As Result
  Dim strCampos As String
  Dim strCamposNoLLave As String
  Dim strLLavePrimaria As String
  Dim strCamposValue As String
  Dim strBindingInsert As String
  Dim strBindingUpdate As String
  
  Dim strCamposUpdate As String
  
  
  
  ' Hacemos el query para detectar la llave primaria
   $result = conexion.Exec("SHOW KEYS FROM  " & FMain.txtTabla.Text & " WHERE Key_name = 'PRIMARY'")
   strLLavePrimaria = $result["Column_name"]
   
   
  ' Identificamos los campos de la tabla nueva
   $result = conexion.Exec("describe " & FMain.txtTabla.Text)


' A partir de aqui vamos creando todo el texto que contendra el archivo tabla.modelo.php

Dim contador As Integer


contador = 0 

While $result.Length > contador
  
 ' CAMPOS PARA EL Select
  If contador == 0 Then 
    strCampos = $result["Field"] & gb.CrLf
     Else 
     strCampos = strCampos & "," & $result["Field"] & gb.CrLf
  Endif
  
  'CAMPOS PARA EL INSERT
  
  If $result["Key"] <> "PRI" Then
    If contador == 1 Then 
      strCamposNoLLave = $result["Field"] & gb.CrLf
      Else 
      strCamposNoLLave = strCamposNoLLave & "," & $result["Field"] & gb.CrLf
    Endif
    
  Endif
  
  
  
    ' CAMPOS PARA EL VALUE
    
    If $result["Key"] <> "PRI" Then
      If contador == 1 Then 
        strCamposValue = ":" & $result["Field"] & gb.CrLf
      Else 
        strCamposValue = strCamposValue & "," & ":" & $result["Field"] & gb.CrLf
        Endif
    Endif
    
     If $result["Key"] <> "PRI"
      strBindingInsert = strBindingInsert & "     $stmt -> bindParam(\":" & $result["Field"] & "\", $datos[\"nuevo" & UCase(Mid$($result["Field"], 1, 1)) & Mid$($result["Field"], 2, 100) & "\"], PDO::PARAM_STR);" & gb.CrLf
    Endif
    
    ' CAMPOS UPDATE
    If $result["Key"] <> "PRI" Then
      
      If contador == 1 Then 
          
          strCamposUpdate = strCamposUpdate & $result["Field"] & "= :" & $result["Field"] 
          
        Else 
          
           strCamposUpdate = strCamposUpdate & "," & $result["Field"] & "= :" & $result["Field"] 
          
      Endif
      
    Endif
    
    strBindingUpdate = strBindingUpdate & "     $stmt -> bindParam(\":" & $result["Field"] & "\", $datos[\"editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\"], PDO::PARAM_STR);" & gb.CrLf

  $result.MoveNext
  contador = contador + 1



Wend

strModelo = ""
strModelo &= "<?php" & gb.CrLf
strModelo &= "require_once \"conexion.php\";" & gb.CrLf
strModelo &= "" & "" & gb.CrLf



strModelo &= "" & "Class Modelo" & UCase(Mid$(FMain.txtTabla.text, 1, 1)) & Mid$(FMain.txtTabla.text, 2, 25) & " {" & gb.CrLf
strModelo &= "" & "   /* =============================================" & gb.CrLf
strModelo &= "" & "     MOSTRAR " & UCase(FMain.txtTabla.text) & gb.CrLf 
strModelo &= "" & "      ============================================= */" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "    Static Public Function mdlMostrar($tabla, $item, $valor) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "       If ($item != Null) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           $stmt = Conexion:: conectar() -> prepare( \"Select " & strCampos

strModelo &= "" & "           From " & FMain.txtTabla.Text & " a WHERE $item =:$item \"); " " " & gb.CrLf 
strModelo &= "" & "" & gb.CrLf


strModelo &= "" & "           $stmt -> bindParam( \":\" .$item, $valor, PDO::PARAM_STR);" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           Try {" & gb.CrLf
strModelo &= "" & "               $stmt -> execute();" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "                Return $stmt -> fetch();" & gb.CrLf
strModelo &= "" & "           } Catch (PDOException $e) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "               $arr = $stmt -> errorInfo();" & gb.CrLf
strModelo &= "" & "                $arr[3] = \" Error \";" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "               If ($e -> getMessage() == 23000) {" & gb.CrLf
strModelo &= "" & "                   $mensaje = \" El registro esta duplicado, Favor de checar el numero de nomina \";" & gb.CrLf
strModelo &= "" & "                   Return $mensaje;" & gb.CrLf
strModelo &= "" & "               } Else {" & gb.CrLf
strModelo &= "" & "                  Return $arr[2];" & gb.CrLf
strModelo &= "" & "              }" & gb.CrLf
strModelo &= "" & "           }" & gb.CrLf
strModelo &= "" & "           " & gb.CrLf
strModelo &= "" & "           " & gb.CrLf
strModelo &= "" & "       } Else {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           $stmt = Conexion:: conectar() -> prepare(\"Select * " "" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           " & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           From " & FMain.txtTabla.Text & " a \"); " "" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           $stmt -> execute();" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           Return $stmt -> fetchAll();" & gb.CrLf
strModelo &= "" & "       }" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "       $stmt -> close();" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "        $stmt = Null;" & gb.CrLf
strModelo &= "" & "   }" & gb.CrLf
strModelo &= "" & "" & gb.CrLf

' REGISTRO

strModelo &= "" & "   /* ==================================================================" & gb.CrLf
strModelo &= "" & "     REGISTRO" & gb.CrLf
strModelo &= "" & "    ==================================================================== */" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "   Static Public Function mdlIngresar($tabla, $datos) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "      $stmt = Conexion:: conectar() -> prepare(\"INSERT INTO " & FMain.txtTabla.Text & "(" & strCamposNoLLave & "" "" & gb.CrLf
strModelo &= "" & "        " & gb.CrLf
strModelo &= "" & "                                                                       )" & gb.CrLf
strModelo &= "" & "                                                                       VALUES(" & strCamposValue & ")" & gb.CrLf
strModelo &= "" & "                          " & gb.CrLf
strModelo &= "" & "                                                                              \"); " "" & gb.CrLf
strModelo &= "" & ""

strModelo &= "" & strBindingInsert & gb.CrLf

strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "       If ($stmt -> execute()) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           Return \"ok\";" & gb.CrLf
strModelo &= "" & "       } Else {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           $arr = $stmt -> errorInfo();" & gb.CrLf
strModelo &= "" & "           $arr[3] = \" Error \";" & gb.CrLf
strModelo &= "" & "          Return $arr[2];" & gb.CrLf
strModelo &= "" & "      }" & gb.CrLf

strModelo &= "" & "      $stmt -> close();" & gb.CrLf

strModelo &= "" & "      $stmt = Null;" & gb.CrLf
strModelo &= "" & "  }" & gb.CrLf



'EDITAR ACTUALIZAR
strModelo &= "" & "  /* ==================================================================" & gb.CrLf
strModelo &= "" & "   EDITAR " & gb.CrLf
strModelo &= "" & "     ================================================================== */" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "   Static Public Function mdlEditar($tabla, $datos) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "       $stmt = Conexion:: conectar() -> prepare(\" UPDATE $tabla SET " & strCamposUpdate & " " "" & gb.CrLf
strModelo &= "" & ""
strModelo &= "" & "                                                                   WHERE id =:" & strLLavePrimaria & "  \"); " "" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & strBindingUpdate
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "       If ($stmt -> execute()) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "           Return \"ok\";" & gb.CrLf
strModelo &= "" & "     } Else {" & gb.CrLf
strModelo &= "" & ""
strModelo &= "" & "          Return \"Error\";" & gb.CrLf
strModelo &= "" & "      }" & gb.CrLf
strModelo &= "" & ""
strModelo &= "" & "     $stmt -> close();" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "      $stmt = Null;" & gb.CrLf
strModelo &= "" & "   }" & gb.CrLf
strModelo &= "" & "   " & gb.CrLf
strModelo &= "" & " " & gb.CrLf & gb.CrLf
strModelo &= "" & "  /* ===================================================================" & gb.CrLf
strModelo &= "" & "     BORRAR USUARIO" & gb.CrLf
strModelo &= "" & "     =================================================================== */" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "  Static Public Function mdlBorrar($tabla, $datos) {" & gb.CrLf

strModelo &= "" & "       $stmt = Conexion:: conectar() -> prepare( \" DELETE From " & FMain.txtTabla.Text & " WHERE id =:id \");" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "       $stmt -> bindParam(\":id\", $datos, PDO::PARAM_INT);" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "      If ($stmt -> execute()) {" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "Return \"ok\";" & gb.CrLf
strModelo &= "" & "      } Else {" & gb.CrLf

strModelo &= "" & "          Return \"Error\";" & gb.CrLf
strModelo &= "" & "      }" & gb.CrLf

strModelo &= "" & "        $stmt -> close();" & gb.CrLf

strModelo &= "" & "       $stmt = Null;" & gb.CrLf
strModelo &= "" & "    }" & gb.CrLf
strModelo &= "" & "" & gb.CrLf
strModelo &= "" & "}" & gb.CrLf

Return strModelo
  
End

Ahora explicamos las partes importantes

Aqui vemos como abrir una conexión a la base de datos, se observa como se usan las variables de configuración programadas en la publicación anterior
Y aquí vemos como ejecutar los querys en la base de datos y guardamos el resultado en la variable $result y luego leemos el nombre de la columna asignase la a la variable strLLavePrimeria

Podemos ejecutar cualquier query por ejemplo conexion.Exec(“select * from usuarios”)
Dentro del código vemos que usamos la función utilerias.strPrimeraMayuscula, pues lo que hace esta función es poner en mayúscula la primera letra de la cadena, en la siguiente publicación pondremos y explicaremos esa función

Página 10 de 13

Creado con WordPress & Tema de Anders Norén