Hola a todos.
Escribo este artículo para compartir con todos vosotros por el pequeño quebradero de cabeza que me ha llevado añadir un simple checkbox de “He leido y acepto la Política de Privacidad” o mensaje similar en el formulario de contacto de Prestashop (en mi caso la versión 1.6.1.12) según indica la Ley de Protección de Datos.
Voy a usar el módulo “Bloque de privacidad de datos del cliente” (customerprivacy) y así nos aseguramos que va a funcionar en la versión de prestashop que estemos usando.
En primer lugar vamos a añadir el Hook del módulo en el fichero “contact-form.tpl“, que se encuentra en la carpeta raíz de nuestro tema, de la siguiente forma:
1 2 |
{$HOOK_CREATE_ACCOUNT_FORM} <div class="submit"> |
A continuación hacemos un “override” del fichero “ContactController.php”. Para no liaros no voy a poner ningún enlace que os explique qué es un override ni como se usa.
Simplemente os voy a decir que teneis que crear un fichero llamado “ContactController.php” en la siguiente carpeta de vuestro prestashop: /override/controllers/front/ y dentro de este fichero que habeis creado le colocais este código:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php class ContactController extends ContactControllerCore { public function initContent() { $this->context->smarty->assign(array( 'HOOK_CREATE_ACCOUNT_FORM' => Hook::exec('createAccountForm'), 'privacy_message' => Configuration::get('CUSTPRIV_MESSAGE', $this->context->language->id) ));parent::initContent(); } public function postProcess() { if (Tools::isSubmit('submitMessage')) Hook::exec('actionBeforeSubmitAccount'); parent::postProcess(); } } |
Digamos que la función de un override es extender con funciones nuevas a un fichero original php desde otro fichero externo y así evitar que cuando se actualice prestashop o el módulo con el que estamos trabajando se modifique el fichero php original y se borre nuestra nueva función o funciones.
Finalmente para que funcione correctamente el checkbox de “Aceptar Política de Privacidad” en el formulario de contacto de Prestashop para cumplir con la LOPD borramos la caché de Prestashop borrando el fichero “class_index.php” que se encuentra dentro de la carpeta /cache/.
Después ya entramos en el módulo “Bloque de privacidad..” y colocamos el texto que queramos así como el enlace a la página CMS de nuestra Política de Privacidad.
Espero que os haya gustado y os funcione.
ACTUALIZACIÓN (13/06/2018)
Hola a todos.
Debimos a los errores que me he ido encontrando para el check de aceptación para el formulario en prestashop usando el módulo ‘Bloque de privacidad de datos del cliente’ gracias a los comentarios de los usuarios, voy a poner otro método descubierto, muy sencillo y eficaz.
Este método mejora el anterior incluyendo un mensaje de error en el mismo formato que presenta prestashop, una ventana roja (según el tema) avisando de la necesidad de marcar la casilla.
1.- Colocamos el check en el archivo tpl del formulario (/themes/”tu-tema”/contact-form.tpl), añadiendo el siguiente código antes del botón submit (botón enviar):
1 2 3 4 5 6 7 |
<div class="col-md-offset-3 col-md-6"> <style>#uniform-lopd { float: left;}</style> <div class="form-group" style="margin-bottom: 24px; text-align: left;"> <input type="checkbox" name="lopd" id="lopd" class="form-control" /> <span>{l s='Aceptar Política de Privacidad'} <a href="{$link->getCMSLink(7)}" target="_blank">{l s='(Más información)'}</a></span> </div> </div> |
Como observación deciros que esta maquetación la he realizado para que se ajustase bien a la plantilla usada, y puede ser necesario ajustarlo según la que uses. También puede modificar el texto usado a tu gusto.
En el link usado ‘getCMSLink(7)’ teneis poner en vez del 7 el id de la página CMS de vuestra Política de Privacidad.
Archivo ContactController.php
2.- Vamos a modificar el archivo /controllers/front/ContactController.php (yo siempre aconsejo usar override, pero para no liar modificamos el mismo fichero):
29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public function postProcess() { if (Tools::isSubmit('submitMessage')) { $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg'); $file_attachment = Tools::fileAttachment('fileUpload'); $message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags. $lopd = Tools::getValue('lopd'); if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) { $this->errors[] = Tools::displayError('Invalid email address.'); } elseif(!$lopd) { $this->errors[] = Tools::displayError('Debes aceptar nuestra política de privacidad'); } elseif (!$message) { $this->errors[] = Tools::displayError('The message cannot be blank.'); } elseif (!Validate::isCleanHtml($message)) { |
Tienes que añadir las lineas 35, 38 y 39.
Comentaros que la primera vez que lo probé no paraba de saiirme un error 500 en la web y era debido simplemente a que me faltaba cerrar unas llaves (}), comprobarlo todo bien ya que funciona sin problema.
Por supuesto también podeis modificar el mensaje de error que yo he colocado.
3.- Finalmente es importante borrar el siguiente fichero de caché, ya que hemos realizado modificaciones en archivos php: /cache/class_index.php. No os preocupeis de borrarlo ya que prestashop lo vuelve a generar pero ya actualizado.
Si te atreves con el check en el registro
En este caso es igual de simple, se trata de modificar el archivo /themes/”tu-tema”/authentication.tpl y añadir un código similar (depende si teneis que retocar la maquetación según vuestra plantilla:
515 516 517 518 519 520 521 522 523 524 525 526 527 |
<div class="checkbox"> <input type="checkbox" name="optin" id="optin" value="1" {if isset($smarty.post.optin) AND $smarty.post.optin == 1} checked="checked"{/if} /> <label for="optin">{l s='Receive special offers from our partners!'}</label> {if array_key_exists('optin', $field_required)} <sup> *</sup> {/if} </div> {/if}*} <div class="checkbox"> <input type="checkbox" name="lopd" id="lopd" /> <span>{l s='Aceptar Política de Privacidad'} <a href="{$link->getCMSLink(7)}" target="_blank">{l s='(Más información)'}</a></span> <sup> *</sup> </div> |
Las líneas a añadir son de la 523 a la 527.
Archivo AuthController.php
Después añadir el siguiente código en el archivo ‘/controllers/front/AuthController.php‘
385 386 387 388 389 390 391 392 393 394 395 396 397 |
protected function processSubmitAccount() { Hook::exec('actionBeforeSubmitAccount'); $this->create_account = true; $lopd = Tools::getValue('lopd'); if(!$lopd) { $this->errors[] = Tools::displayError('Debes aceptar nuestra política de privacidad'); } if (Tools::isSubmit('submitAccount')) { $this->context->smarty->assign('email_create', 1); } |
Las lineas a añadir son de la 389 a la 391 dentro de la clase protegida processSubmitAccount(). Debido a ser protected no es posible realizar un override.
Os hago la reseña que los número de línea de código incluidos pueden ser aproximados, ya que depende de cada plantilla instalada.
Y repito, es importante que os fijeis en abrir y cerrar bien todas las llaves para evitar el error 500 en vuestra web.
Pues esto es todo, espero que os sirva de ayuda y pido disculpas del anterior que estaba produciendo errores.
Muchas gracias, se agradece la ayuda, ha quedado perfecto… ;-}
Gracias a tí por comentar y encantado de que te haya servido.
wooow! Muchas gracias. Voy a probarlo. Una pregunta, ¿se podría usar esto mismo para añadir el checkbox al bloque de suscripción del newsletter?
Hola muchas gracias por tu tutorial pero tengo un problema, he seguido todos la pasos que has indicado pero ahora caundo intentio manda un mensaje me sale el siguiente mensaje: Error 1
Si acepta los términos del mensaje Privacidad de los datos del cliente, haga clic en la casilla de verificación que aparece a continuación.
pero no aparece dicho chekout ni antes ni despues .
¿prodrias ayudarme?
Muchas gracias de antemano
Hola Peter.
En primer lugar disculpa la demora en la respuesta.
Pienso que debe funcionar de igual forma si incluyes el hook en el fichero tpl del modulo newsletter que tengas.
Si lo pruebas puedes comentar aquí el resultado.
Un saludo.
Hola Julian.
Disculpa la demora en la contestación, no se si ya habrás solucionado el problema.
Lo que se me ocurre es que pueda ser por la caché, has vaciado la caché de prestashop ? Y si es así, prueba a vaciar la caché de tu navegador, yo con chrome últimamente estoy experimentando problemas con la caché con cambios realizados en web y no me los actualiza. También puedes probar con otros navegadores a ver.
Qué versión de prestashop tienes instalada ?
Un saludo.
Gracias Juan por la aportación. Está muy bien explicado (sin liarnos) y funciona perfectamente :). Un abrazo.
Muchas gracias tí Ramón. Me alegro que te haya sido de utilidad.
Antes de nada muchísimas gracias por este tutorial.
Tengo una consulta. Tengo que desactivar la aceptación de la política de privacidad en el carrito o registro, porque ya me la hace otro módulo de one-page-checkout. La cosa es que sí que quiero que se acepte en el formulario de contacto. ¿Cómo se podría desanclar ese hook del módulo de one-page-checkout?
Hola Javier.
Muchas gracias por tu comentario.
Pues mira, no sé el módulo onepagecheckout que estás usando, pero creo que para desactivarlo tendrías que entrar en el php del módulo y allí comentar la parte del checkout, ya que pienso que estárá integrada en el mismo módulo, al menos por los que he probado yo.
Ya me comentas si lo has encontrado.
Yo tengo una duda, resulta que ya tenia creado el ContactController.php con el codigo que genera el modulo eicaptcha. Total, que si intento añadir los dos codigos siempre obtengo pantalla en blanco. El codigo que mete el eicaptcha es este. ¿Se podrian añadir los dos de alguna forma?. Gracias.
redirect_after)) {
parent::redirect();
}
if (!$this->content_only && ($this->display_header || (isset($this->className) && $this->className))) {
parent::initHeader();
}
parent::initContent();
if (!$this->content_only && ($this->display_footer || (isset($this->className) && $this->className))) {
parent::initFooter();
}
parent::display();
die;
}
}
Hola, funciona con prestashop 1.7??, gracias.
Buenas!
He hecho todos los pasos y funciona correctamente, el problema es que cuando borro el caché de prestashop desde las opciones de Rendimiento me desaparece el checkbox del contacto, y no vuelve a aparecer hasta que borro de nuevo el archivo class_index.php ¿alguna idea de qué puede estar pasando?
Gracias
Hola Jose.
No es compatible con prestashop 1.7 porque el módulo que utilizo “Bloque de privacidad de datos del cliente” no existe en la nueva versión.
Próximamente colgaré algo parecido para 1.7.
Un saludo.
habilitado también, pero se consigue que se muestre el check box en https://www.rhhotelamenities.com/es/contactar,
Buenas,
Me ha funcionado perfectamente. Muchas gracias por el aporte.
Muchas gracias a tí por comentar.
Muchas gracias por el tutorial, funciona bien excepto por que aunque no se seleccione el checkbox el mensaje de contacto se envía igualmente.
¿Sabes a qué es debido esto y cómo podría solucionarlo?
Un saludo.
Hola Joan, gracias por tu comentario.
Voy a revisarlo y te digo.
Buenas tardes Juan Carlos,
¿Pudiste ver algo?
Muchas gracias.
Hola Joan.
Has probado a reinicializar el módulo que hemos manipulado ?
En el listado de módulos, despliegas el botón Modificar a la derecha del módulo y pulsas Reinicializar.
Dime algo si se te soluciona o sigo estudiándolo.
hola, querría decir, NO se consigue,
espero que nos ayudes al respecto,
gracias
hola Juan,
hemos hecho Reinicializar el módulo, pero sigue sin aparecer el checkbox en https://www.rhhotelamenities.com/es/contactar,
agradecemos antemano su respuesta,
Buenas tardes Juan Carlos,
Sí, he reiniciado el módulo y sigue igual.
¿Tienes alguna idea de por qué pasa esto?
Muchas gracias.
Buenos días.
Te invito a que pruebes la actualización que he puesto con otro método, que no tiene errores e incluye mensaje de error del sistema si no se activa el check
Hola Joan.
Revisa la actualización que he puesto con otro método más sencillo y completo que soluciona el problema.
Hola Alvaro.
He puesto una actualización del post usando otro método y el mismo funciona perfectamente junto al módulo eicaptcha. Comprobado.
Hola Juan.
Te invito a que pruebes el nuevo método que he publicado como actualización que funciona perfectamente y además, incluye error del sistema para avisar que tienes que aceptar el check.
Muchas gracais por tu trabajo Juan CM mora
Casi me funciona perfecto…pero…
Cuando no marco el check de aceptar la prolitica de privacidad en el formulario de contacto y le doy a enviar, efectivamente no lo envía y da un error superior en rojo (como deberia ser) pero pone en este error “Error 1” nada más…ni mensaje ni nada…
Puedes probarlo aquí:
https://www.chasanga.es/contactanos
¿Sabes por que no pone el mensaje de “Debes aceptar la politica de privacidad”?
Hola Carlos.
Comprueba que has implementado bien las lineas 35, 38 y 39 en el fichero ContactController.php (si no lo has hecho con override y posteriormente has actualizado prestashop se te va a machacar el script introducido).
Aquí es donde se controla ese error, si no está activado el check visualiza el mismo).
Un saludo.
Gracias.
En el ContacController.php lo modifiqué, lo tengo así:
class ContactControllerCore extends FrontController
{
public $php_self = 'contact';
public $ssl = true;
/**
* Start forms process
* @see FrontController::postProcess()
*/
public function postProcess()
{
if (Tools::isSubmit('submitMessage')) {
$extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
$file_attachment = Tools::fileAttachment('fileUpload');
$message = Tools::getValue('message'); // Html entities is not usefull, iscleanHtml check there is no bad html tags.
$lopd = Tools::getValue('lopd');
if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
$this->errors[] = Tools::displayError('Invalid email address.');
} elseif(!$lopd) {
$this->errors[] = Tools::displayError('Debes aceptar nuestra política de privacidad');
} elseif (!$message) {
$this->errors[] = Tools::displayError('The message cannot be blank.');
} elseif (!Validate::isCleanHtml($message)) {
Solucionado Carlos.
Algo había mal en tu ContactController.php, te he puesto la función postProcess() limpia en un override y ahora te funciona perfectamente.
Un cordial saludo.
Howdy! Someone in my Facebook group shared this website
with us so I came to give it a look. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers!
Fantastic blog and amazing design and style.
My web site; cannabis gummies
Hello! This is my 1st comment here so I just wanted to give a quick shout out and tell you I genuinely
enjoy reading through your blog posts. Can you
recommend any other blogs/websites/forums that cover the same
topics? Thanks a ton!
Have a look at my webpage :: weed near me
When I originally commented I appear to have clicked on the -Notify me when new comments
are added- checkbox and now whenever a comment is added I receive 4 emails with
the same comment. There has to be an easy method you
are able to remove me from that service? Appreciate it!
My page delta 8 THC
Undeniably believe that which you stated. Your favorite justification appeared to be
on the web the easiest thing to be aware of. I say to
you, I certainly get irked while people think about worries that they just do not
know about. You managed to hit the nail upon the top and also defined out the whole thing
without having side effect , people could take a signal.
Will probably be back to get more. Thanks
Also visit my homepage – THC Gummies
When I originally commented I appear to have clicked the
-Notify me when new comments are added- checkbox and now each
time a comment is added I receive 4 emails with the same
comment. There has to be a means you can remove me from that service?
Thanks!
Feel free to visit my web-site :: delta 8 THC gummies
whoah this weblog is magnificent i really like
studying your posts. Keep up the great work!
You know, lots of people are searching around for this info, you could help them greatly.
my webpage buy weed online
I’m curious to find out what blog platform you happen to be working with?
I’m having some minor security issues with my latest website and I’d like to find something more secure.
Do you have any solutions?
I visited multiple blogs but the audio feature for audio songs present
at this web site is in fact wonderful.
Feel free to visit my site buy Instagram followers
Pretty part of content. I just stumbled upon your blog and in accession capital to assert that I get in fact
loved account your blog posts. Anyway I’ll be subscribing for your augment and even I success you get right of entry to consistently quickly.
Can you tell us more about this? I’d love to find out more details.
Here is my blog post :: delta 8 gummies pain relief
I am truly thankful to the owner of this web site who has
shared this enormous article at at this place.
Stop by my web-site – baby aspirin for puppies
Undeniably imagine that that you said. Your favourite reason seemed to
be at the web the simplest factor to bear in mind
of. I say to you, I certainly get irked whilst other folks think about concerns that they plainly don’t
recognise about. You controlled to hit the nail upon the highest and also defined out the whole thing with no need side effect , other
people can take a signal. Will likely be again to get more.
Thanks
Here is my homepage :: cbd gummies for pain
I’m not certain the place you’re getting your information, however good topic.
I must spend a while finding out much more
or understanding more. Thank you for great info I used to be searching for this information for my mission.
Also visit my site … best kratom
I don’t even know how I ended up here, but
I thought this post was great. I don’t know who you are but
definitely you are going to a famous blogger if you aren’t already 😉 Cheers!
Feel free to visit my web-site cbd for sale
Amazing! Its genuinely remarkable post, I have got much
clear idea about from this piece of writing.
my page :: maeng da kratom reviews
I am sure this article has touched all the internet viewers, its really really
pleasant piece of writing on building up new website.
click me here온라인카지노
yang
First off I would like to say fantastic blog! I had a quick question which I’d like to ask if
you don’t mind. I was interested to know how you center yourself
and clear your thoughts prior to writing. I’ve had trouble clearing my mind in getting my thoughts out there.
I truly do enjoy writing but it just seems like the first 10 to 15 minutes tend to
be wasted just trying to figure out how to begin. Any recommendations or hints?
Thank you!
Here is my website – cbd capsules for pain
It is actually a great and helpful piece of information. I am glad
that you shared this helpful information with us.
Please keep us informed like this. Thanks for sharing.
Here is my page – buy baked bros cbd gummies
I know this web page gives quality dependent articles or reviews and other material, is there any other
site which presents these kinds of information in quality?
I constantly spent my half an hour to read this weblog’s
articles or reviews daily along with a cup of coffee.
Nice post, na-share ko na sa mga kaibigan ko.
좋은 게시물, 나는 그것을 내 친구들과 공유했습니다.
좋은 게시물, 나는 그것을 내 친구들과 공유했습니다.
Buen post, lo he compartido con mis amigos.
Güzel bir yazı, arkadaşlarımla paylaştım.
Bel article, je l’ai partagé avec mes amis.
منشور جميل ، لقد شاركته مع أصدقائي.
Гарний пост, я поділився ним із
друзями.
منشور جميل ، لقد شاركته مع أصدقائي.
Posting yang bagus, saya telah membagikannya dengan teman-teman saya.
منشور جميل ، لقد شاركته مع أصدقائي.
Dejligt indlæg, jeg har delt det med mine venner.
Dejligt indlæg, jeg har delt det med mine venner.
Fint innlegg, jeg har delt det med vennene mine.
Nice post, na-share ko na sa mga kaibigan ko.
Belo post, compartilhei com meus amigos.
Bel post, l’ho condiviso con i miei amici.
Bel article, je l’ai partagé avec mes amis.
Belo post, compartilhei com meus amigos.
Posting yang bagus, saya telah membagikannya dengan teman-teman saya.
Güzel bir yazı, arkadaşlarımla paylaştım.
Хороший пост, поделился с друзьями.
Хороший пост, поделился с друзьями.
Buen post, lo he compartido con mis amigos.
Thanks very interesting blog!
Asking questions are really pleasant thing if you are not understanding anything totally, except this piece of writing presents nice understanding even.
My partner and I absolutely love your blog and find many of your post’s to be exactly I’m looking for.
Do you offer guest writers to write content for you?
I wouldn’t mind writing a post or elaborating on a few of the subjects you write regarding here.
Again, awesome weblog!
Hi there, its fastidious paragraph about media print, we
all understand media is a enormous source of facts.
magnificent issues altogether, you just won a new reader.
What might you recommend in regards to your submit that you just made
a few days in the past? Any positive?
Bel article, je l’ai partagé avec mes amis.
Quality content is the secret to interest the users
to pay a quick visit the website, that’s what this web page
is providing.
Thank you for sharing your thoughts. I really appreciate your efforts and I will be waiting for your
next post thanks once again.
Hey There. I found your blog using msn. This is an extremely well written article.
I will be sure to bookmark it and come back to read
more of your useful information. Thanks for the post.
I’ll certainly comeback.
Everything is very open with a very clear clarification of the issues.
It was definitely informative. Your site is very helpful.
Thank you for sharing!
What’s up it’s me, I am also visiting this web page daily, this web page is genuinely pleasant
and the viewers are really sharing fastidious thoughts.
Hello just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading correctly.
I’m not sure why but I think its a linking issue. I’ve tried it
in two different web browsers and both show the same
results.
You actually make it seem so easy with your presentation but I find this matter to be really something which I think I would never understand.
It seems too complicated and very broad for me. I’m looking
forward for your next post, I will try to get the hang of it!
Quality articles or reviews is the crucial to invite the people to pay
a visit the website, that’s what this website
is providing.
This post provides clear idea designed for the
new people of blogging, that in fact how to do running a blog.
Hi there, I enjoy reading all of your article. I wanted to
write a little comment to support you.
Your style is unique in comparison to other folks
I have read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I’ll just
bookmark this page.