Jump to content

GKentaurus

Members
  • Posts

    26
  • Joined

  • Last visited

1 Follower

About GKentaurus

  • Birthday 04/30/1989

Contact Methods

Profile Information

  • Location
    Colombia
  • Interests
    Hamburguers!! And code... obviously hehe...
  • Activity
    Developer

Recent Profile Visitors

1,794 profile views

GKentaurus's Achievements

Newbie

Newbie (1/14)

1

Reputation

  1. Good news everyone! Confirmed: This code line add all the HTML content into the authentication.tpl for the register form. YOU!... little piece of code... Knowing this, now if I need to do more tests, if I modify the authentication.tpl file, change to add the fields I need. On the other hand, the question that was of minor importance, happens to have more relevance: Why does the AuthController override not work correctly? He's just overriding what he wants and not what I need. Stay connected on this channel. More news on this issue soon.
  2. Buenas noticias amigos: Confirmado: Esta linea de código añade todo el contenido HTML del archivo authentication.tpl al formulario de registro! Tu, pequeño pedazo de código... Sabiendo esto, ahora si necesito hacer mas pruebas, si modificando el archivo authentication.tpl, cambia para agregar los campos que necesito. Por otro lado, la pregunta que era de menor importancia, pasa a tener mayor relevancia: ¿Por qué el override de AuthController no funciona correctamente? Solo está haciendo override a lo que quiere y no a lo que necesito. Sigan conectados en este. Pronto encontrarán mas noticias sobre este problema.
  3. Creo que esto es una buena noticia: Encontré este código cerca de la linea 165 en AuthController: $return = array( 'hasError' => !empty($this->errors), 'errors' => $this->errors, 'page' => $this->context->smarty->fetch($this->template), 'token' => Tools::getToken(false) ); $this->ajaxDie(Tools::jsonEncode($return)); Bueno... $this->template debería contener el template que he colocado antes (pero no, es una mentira, y no se por qué) y contiene el original authentication.tpl. Ahora, en el archivo authentication.js, ubicado en el carpeta JS del tema, encontré este script: function submitFunction() { $('#create_account_error').html('').hide(); $.ajax({ type: 'POST', url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: "json", headers: {"cache-control": "no-cache"}, data: { controller: 'authentication', SubmitCreate: 1, ajax: true, email_create: $('#email_create').val(), back: $('input[name=back]').val(), token: token }, success: function (jsonData) { console.log(jsonData); if (jsonData.hasError) { var errors = ''; for (error in jsonData.errors) //IE6 bug fix if (error != 'indexOf') errors += '<li>' + jsonData.errors[error] + '</li>'; $('#create_account_error').html('<ol>' + errors + '</ol>').show(); } else { // adding a div to display a transition $('#center_column').html('<div id="noSlide">' + $('#center_column').html() + '</div>'); $('#noSlide').fadeOut('slow', function () { $('#noSlide').html(jsonData.page); $(this).fadeIn('slow', function () { if (typeof bindUniform !== 'undefined') bindUniform(); if (typeof bindStateInputAndUpdate !== 'undefined') bindStateInputAndUpdate(); document.location = '#account-creation'; }); }); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { error = "TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus; if (!!$.prototype.fancybox) { $.fancybox.open([ { type: 'inline', autoScale: true, minHeight: 30, content: "<p class='fancybox-error'>" + error + '</p>' }], { padding: 0 }); } else alert(error); } }); } Cuando el controller "authentication" (de acuerdo a lo que he visto, sería el mismo AuthController, pero no se por qué tienen diferente nombre) retorna o responde con un success sobre el Ajax, captura u obtiene todo el código HTML del archivo authentication.tpl por esta linea mostrada en el primer código de esta respuesta: 'page' => $this->context->smarty->fetch($this->template), Y almacenada en jsonData.page, para ser enviado por la función de JQuery ".html()" Imprimiendo con console.log(jsonData), obtengo esto: {hasError: false, errors: Array(0), page: "<h1 class="page-heading">Crear una cuenta</h1>↵↵↵ …sup>Campo requerido</span></p>↵ </div>↵ </form>↵", token: "870c36a04fc1d9b250707cdd6c7ca583"} En este JSON, ustedes pueden ver la llave page del array. Pero me sigo preguntando... "si coloqué mi propio template, ¿Por qué el AuthController sigue usando el archivo authentication.tpl por defecto? Gracias chicos,... son lo máximo... Intentaré reemplazar en el override $return = array( 'hasError' => !empty($this->errors), 'errors' => $this->errors, 'page' => $this->context->smarty->fetch($this->template), 'token' => Tools::getToken(false) ); $this->ajaxDie(Tools::jsonEncode($return)); $this->template por la dirección de mi propia plantilla. Sigan conectados en este. Pronto encontrarán mas noticias sobre este problema.
  4. I think this is a Good News: I find this core near the line 165 on the AuthController: $return = array( 'hasError' => !empty($this->errors), 'errors' => $this->errors, 'page' => $this->context->smarty->fetch($this->template), 'token' => Tools::getToken(false) ); $this->ajaxDie(Tools::jsonEncode($return)); So, $this->template must contain the template setted before (but no, it's a lie, I don't know why) and contain the original authentication.tpl. Now, in the authentication.js located in the js folder on the template path, I find this script: function submitFunction() { $('#create_account_error').html('').hide(); $.ajax({ type: 'POST', url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: "json", headers: {"cache-control": "no-cache"}, data: { controller: 'authentication', SubmitCreate: 1, ajax: true, email_create: $('#email_create').val(), back: $('input[name=back]').val(), token: token }, success: function (jsonData) { if (jsonData.hasError) { var errors = ''; for (error in jsonData.errors) //IE6 bug fix if (error != 'indexOf') errors += '<li>' + jsonData.errors[error] + '</li>'; $('#create_account_error').html('<ol>' + errors + '</ol>').show(); } else { // adding a div to display a transition $('#center_column').html('<div id="noSlide">' + $('#center_column').html() + '</div>'); $('#noSlide').fadeOut('slow', function () { $('#noSlide').html(jsonData.page); $(this).fadeIn('slow', function () { if (typeof bindUniform !== 'undefined') bindUniform(); if (typeof bindStateInputAndUpdate !== 'undefined') bindStateInputAndUpdate(); document.location = '#account-creation'; }); }); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { error = "TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus; if (!!$.prototype.fancybox) { $.fancybox.open([ { type: 'inline', autoScale: true, minHeight: 30, content: "<p class='fancybox-error'>" + error + '</p>' }], { padding: 0 }); } else alert(error); } }); } When the "authentication" controller (according to what I have seen, it's the same AuthController, but I don't know why have a different name) return or respond with a success, this script get the authentication.tpl HTML code for this line in the first code shown: 'page' => $this->context->smarty->fetch($this->template), And stored in the jsonData.page, to be sent via .html() JQuery function. Printing with console.log(jsonData), I got this: {hasError: false, errors: Array(0), page: "<h1 class="page-heading">Crear una cuenta</h1>↵↵↵ …sup>Campo requerido</span></p>↵ </div>↵ </form>↵", token: "870c36a04fc1d9b250707cdd6c7ca583"} in the JSON String, you can see the key page. But I keep wondering "if I set my own template, why the AuthController still using the default authentication.tpl file? Thanks people... you're awesome... I wll try to replace in this script: $return = array( 'hasError' => !empty($this->errors), 'errors' => $this->errors, 'page' => $this->context->smarty->fetch($this->template), 'token' => Tools::getToken(false) ); $this->ajaxDie(Tools::jsonEncode($return)); $this->template for the path of my own template. Stay connected on this channel. More news on this issue soon.
  5. Answering myself: Yep the file is themes/default_bootstrap/js/authentication.js Sending by Ajax, the email address to validate if already registered. The initContent(), processSubmitLogin() y processSubmitAccount() functions is sending information, with this: $this->AjaxDie(Tools::jsonEncode($return)); only for errors Keep commentings if I found some news
  6. Me voy respondiendo a mi mismo: Si, es el archivo themes/default_bootstrap/js/authentication.js Está enviando por Ajax el correo electrónico para validar si el correo ya existe o no. La función initContent(), processSubmitLogin() y processSubmitAccount() están enviando por la información, por medio de $this->AjaxDie(Tools::jsonEncode($return)); principalmente para los errores... Iré comentando mientras voy avanzando.
  7. Hi everyone: Greetings from Colombia (co) I've been looking for heaven, earth and sea a solution to the next issue, but first I'll tell you a little introduction to what I'm doing: I'm developing a module to the Prestashop v1.6.1.17, that allows upload products, clients, sales correctly processed and paid, to a Electronic Billing platform. This platform, like my country, require 3 important fields that registration form from Prestashop, doesn't allow: Know if the registered client is a person or is a company Get the Identification type (like license driver for a person, or Company ID for a company, obviously) Get the Identification number. So... I feel that someone will reply me with "Easy, in the Address form, you have a field to put and catch the identification number ;)", and it's true... you're right, but that field (Identification Number) isn't unique, and in my country... that number is unique. I've been able to overtake absolutely everything (even altering the Customer table to add these 3 columns, without needing to broke anything at all), I have managed to make an Override of the Customer class and the AuthController FrontController to add more variables when modifying the form, but my problem is trying to modify this form: Again I feel that someone will reply me with "Easy, go to the themes/default-bootstrap/authentication.tpl file and edit all you need", and again I'll tell you "you're right", that's the file I need to modify. But my objective is load this form from my module, not from the theme folder. I use override all AuthController to avoid some errors on FrontOffice, but in the override, I modified in the initContent function, this lines: Original AuthController code: // Just set $this->template value here in case it's used by Ajax$this->setTemplate(_PS_THEME_DIR_.'authentication.tpl'); Override AuthController code: // Just set $this->template value here in case it's used by Ajax$module_dir_override_tpl = _PS_MODULE_DIR_ . 'my-module/views/templates/front/override/';$this->context->smarty->assign('mts_dir', $module_dir_override_tpl);$this->setTemplate($module_dir_override_tpl . 'authentication.tpl'); The difference is asign to a variable the Prestashop Module Directory path (changing "_PS_THEME_DIR_" for "_PS_MODULE_DIR_" constants), adding the complete file path. Everything it's ok so far, because when I go to the Sign up / Sign in section, all load correctly. The page loads "initially" this section: Confirmed: loads from modules/my-module/views/templates/front/override/authentication.tpl If I edit anything in this section, the template load correctly... works fine, but the problem starts when I click on the Create an Account button: Confirmed: loads from themes/default-bootstrap/authentication.tpl The page loaded is like the original themes/default-bootstrap/authentication.tpl, ignoring all the changes that I made before. Hours try to know what happen, I rename the file from this: themes/default-bootstrap/authentication.tpl To this: themes/default-bootstrap/authentication2.tpl When I reload the page and click in the Create an Account button, i got this: I started searching with a code editor if there was any additional {include} (aparte from the errors.tpl file), but there are only Hooks, conditionals, and the form I need to load. Maybe I need to check the Hooks, if it is really necessary to implement one (since in itself the operation of the code is between the BackOffice and the FrontOffice, without any hook, except the DisplayHeader hook... I thinks I don't need any other, it is only to load css and js ... I think) Will there be any JavaScript that is loading the original form from the theme path and not from the module path? I dare to blame a JS because the error that comes out is "after" that the form is loaded ... if there was an error, it would not load anything on the page ... a blank page nothing else (or in the worst case, a 500 error). And the other problem I have (to a lesser degree) is, why when I uninstall the module, does not remove all the corresponding files from the Override folder? Deleting the class_index.php from the cache folder will be manual and mandatory, but only the override of Customer is the one that stays there. Thanks
  8. Hi Zorrobsas Try to make an override for all functions and modify only that you need to edit. I mean... Copy the StockAvailable.php original class file Paste into the override/classes/stock/ folder Modify the class and extend from the core Edit the function that you need In some cases, it works. I hope this can be useful.
  9. Hi everyone: To BackOffice try this: public function hookBackOfficeHeader(){ if (Tools::getValue('configure') == $this->name || Tools::getValue('module_name') == $this->name) { $this->context->controller->addJS($this->_path.'views/js/back.js'); $this->context->controller->addCSS($this->_path.'views/css/back.css'); [spam-filter] To FrontOffice try this: public function hookDisplayHeader(){ if ('order' === $this->context->controller->php_self) { $this->context->controller->registerStylesheet('modules-front', 'modules/'.$this->name.'/views/css/front.css', array('media' => 'all', 'priority' => 150)); $this->context->controller->registerJavascript('modules-front', 'modules/'.$this->name.'/views/js/front.js', array('position' => 'bottom', 'priority' => 150)); [spam-filter] Hope this be usefull and can help you Edit: Obviously, install the hooks you need
  10. Hola Fox_sys: Para evitar errores, la eliminación de registros no es algo bien visto, menos cuando se trata de productos, porque 1 solo producto puede tener mas o menos las siguientes relaciones (como por generalizar): Tabla de traducciones de los nombres y descripciones Tabla de atributos Tabla de combinaciones Ordenes Carritos de compra Lista de favoritos de tus clientes (si esta disponible) Por lo tanto es mejor desactivar los productos, y en el BackOffice manejar la consulta del listado de productos, de forma predeterminada, como "mostrar solo activos". Ya, si estás decidido en borrar todos los productos, puedes intentar acceder a la base de datos directamente y borrar la siguiente información: PD: No lo he hecho y no lo garantizo, por lo tanto te sugiero que hagas una copia tanto de todo el directorio de Prestashop instalado en tu hosting o servidor, al igual que de la base de datos antes de empezar cualquier operación. Viendo la información de todas las tablas, deberías eliminar el contenido de las siguientes tablas: category_product feature_product image image_lang image_shop image_type layered_price_index layered_product_attribute product product_attachment product_attribute product_attribute_combination product_attribute_image product_attribute_shop product_carrier product_country_tax product_download product_group_reduction_cache product_lang product_sale product_shop product_supplier stock_available Puedes seleccionar la tabla mencionada, ir a Operaciones y seleccionar Truncate: Como ya lo mencioné, no he probado nunca hacer un borrado masivo, sin embargo puedes intentarlo. Lo malo puede ser que, como los productos están relacionados con pedidos, órdenes de compra, carritos de compra antiguos, etc, consigas muchos errores. Los pedidos y órdenes de compras están vinculados a un carrito de compra (principalmente los no abandondos) por lo tanto, haz un backup de toda tu información antes de proceder. Quedamos atentos a tu respuesta.
  11. Hola Rimanded: Puede que suene tonto pero, ¿ya intentaste hacer la búsqueda por medio de etiquetas? Recuerdo que en la versión 1.6.1.x era un buen método.
  12. Hola Pedro: No estoy muy familiarizado con el área de Themes, pero si con el de módulos. En Prestashop 1.7 se implementó una nueva forma de registrar tanto JS como CSS, ya sea en el Header o en el Footer. Espero estas lineas puedan servirte de ayuda: public function hookDisplayHeader() { // Si está cargado el controller Order, haga if ('order' === $this->context->controller->php_self) { $this->context->controller->registerStylesheet('modules-front', 'modules/'.$this->name.'/views/css/front.css', array('media' => 'all', 'priority' => 150)); $this->context->controller->registerJavascript('modules-front', 'modules/'.$this->name.'/views/js/front.js', array('position' => 'bottom', 'priority' => 150)); } } Quedamos atentos a tu respuesta.
  13. Hola Sofía: Para esto, se debe desarrollar un módulo que haga según lo que entendí, mostrar datos de contacto de alguien (un asesor comercial supongo), dependiendo del grupo de cliente al cual pertenezca cada cliente de tu tienda en la sección Mi Cuenta. En términos de desarrollo, debes: Revisar si los hooks necesarios para mostrar la debida información. Hacer una instalación de una tabla en la base de datos, que permita almacenar de forma dinámica la información del contacto Hacer una consulta a la base de datos, para saber a que grupo pertenece el cliente Descargar la información de la base de datos del contacto asignado al grupo Mostrar por medio de una plantilla la información deseada O por otra parte, si no te quieres liar con el desarrollo de un modulo, puedes: Hacer un override del controller MyAccountController.php (si mal no estoy) Añadir una consulta a la base de datos directamente desde el override para identificar a que grupo pertenece ese cliente en especifico Con un condicional, dependiendo de los grupos a los que pertenezca, que cargue los datos de contacto que necesitas mostrar. Espero haber sido de ayuda. Quedo pendiente de tu respuesta.
  14. Hola a todos: He estado buscando por cielo, tierra y mar una solución al siguiente inconveniente, pero primero les haré una pequeña introducción a lo que estoy haciendo: Me encuentro desarrollando un módulo para la versión de Prestashop 1.6.1.17 (Last Stable), que permita subir los productos, los clientes y las ventas procesadas y debidamente pagadas, a un sistema de Facturación Electrónica. Este sistema de facturación, al igual que por requerimientos legales de mi país (Colombia), se debe solicitar 3 cosas, que no son soportadas directamente por los formularios de registro de Prestashop: Tipo de persona (Persona Natural o Persona Jurídica) Tipo de Documento (Cédula de Ciudadanía, Cédula de Extranjería, etc) Número de Documento Se que ya alguno en este momento, tiene en mente "Tranquilo, en el formulario de Direcciones (Address) hay un campo para eso ;)", pero el problema es, que ese campo llamado "Identificación" no me sirve, puesto que en cada dirección, la identificación puede ser distinta, y el objetivo de una identificación es que sea único. He podido adelantar absolutamente todo (incluso alterar la tabla Customer para añadir estas 3 columnas, sin la necesidad dañar absolutamente nada hasta el momento), he logrado hacer un Override de la clase Customer y del FrontController AuthController para agregar mas variables a la hora de modificar el formulario, pero mi problema viene intentando modificar este formulario: Y se que más de uno tiene en mente "Tranquilo, ve a themes/default-bootstrap/, busca el archivo authentication.tpl, modifícalo a tu gusto y ya", para lo cual les digo, tienen toda la razón... ese es el archivo. Pero mi objetivo es que ese formulario no cargue desde esa dirección, sino desde la dirección que yo establezco en mi módulo: Código original de AuthController: // Just set $this->template value here in case it's used by Ajax $this->setTemplate(_PS_THEME_DIR_.'authentication.tpl'); Código del Override de AuthController: // Just set $this->template value here in case it's used by Ajax $module_dir_override_tpl = _PS_MODULE_DIR_ . 'my-module/views/templates/front/override/'; $this->context->smarty->assign('mts_dir', $module_dir_override_tpl); $this->setTemplate($module_dir_override_tpl . 'authentication.tpl'); La diferencia fue directamente asignar a una variable el directorio de Prestashop para los módulos (cambiando las constantes definidas "_PS_THEME_DIR_" por "_PS_MODULE_DIR_"), agregándole la ruta completa del archivo. Por motivos de seguridad, hice el override completo para que no salieran problemas, y solo modifiqué las líneas que les comenté (es como haber editado en el archivo original, la función mencionada) Hasta ahí vamos bien, porque cuando se accede a la sección de Iniciar Sesión, todo carga como debe ser. Carga "inicialmente" esta sección . Confirmado que el archivo carga desde modules/my-module/views/templates/front/override/authentication.tpl Si le modifico un titulo o añado algo ahí, funciona de maravilla, pero el problema radica a partir de cuando doy clic en el botón "Crear cuenta": Confirmado que el archivo carga desde themes/default-bootstrap/authentication.tpl (ya les digo por qué) Vuelve y aparece todo lo que está en el archivo original, y no lo que está en mi archivo modificado. Después de muchas horas de darle vueltas a eso, y por querer descartar las cosas definitivamente, modifiqué el archivo themes/default-bootstrap/authentication.tpl por themes/default-bootstrap/authentication2.tpl Y cuando fui a dar clic nuevamente en Crear cuenta, sale este error: Me puse a buscar con un editor de código si existía algún {include} de algún TPL (template de Smarty) adicional, pero solo hay Hooks, condicionales y el formulario que necesito que cargue. Quizás me falte revisar los Hooks, si es que es verdaderamente necesario implementar uno (ya que en sí el funcionamiento del código esta entre el BackOffice y el FrontOffice, sin ningún hook, excepto el DisplayHeader, tranquilos, no es necesario ningún otro, solo es para cargar css y js... creo) ¿Habrá algun JavaScript que esté cargando el formulario original desde el tema y no desde el módulo? Me atrevo a echarle la culpa a un JS porque el error que sale es "después" de que se carga el formulario... si hubiese un error, no cargaría nada en la página... una página en blanco nada mas (o en el peor de los casos, un error 500). Y el otro problema que tengo (ya en menor grado) es, ¿Por qué cuando desinstalo el módulo, no quita todos los archivos correspondientes de la carpeta Override? Borrar el class_index.php de la carpeta cache se que es manual y obligatorio, pero solo el override de Customer es el que se queda ahí. De antemano, gracias.
  15. Hola Doruko: Puedes entonces probar con ese módulo que te mencioné anteriormente, pero te recomiendo hacer un backup de todo, ya que este módulo suele generar inconvenientes con el SEO nativo de Prestashop, hasta donde tengo entendido. Comentanos tu experiencia y avisanos como van las cosas.
×
×
  • Create New...