Buenas chicos, muchas gracias de antemano, gracias a vuestras dudas y ayuda he conseguido avanzar bastante en el tema prestashop, pero me cruzo con el siguiente problema.
Necesito un formulario de contacto personalizado y todos los plugins que hay no cumplen la función que deseo, por ello me lanzo a programar mi propio formulario, para ello realizo lo siguiente:
En el directorio raíz de mi prestashop tengo paginaejemplo.php
<?
require(dirname(__FILE__).'/config/config.inc.php');
Tools::displayFileAsDeprecated();
Tools::redirect('index.php?controller=paginaejemplo', __PS_BASE_URI__, null, 'HTTP/1.1 301 Moved Permanently');
?>
Con este código llamamos al controlador.
Dentro de la carpeta controllers/front incluyo el fichero paginaejemploController.php que contiene el siguiente código:
<?php
/*
* 2007-2014 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2014 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class paginaejemploControllerCore extends FrontController{
public $php_self = 'paginaejemplo';
public function setMedia(){
parent::setMedia();
$this->addCSS(_THEME_CSS_DIR_.'paginaejemplo.css');
}
public function init(){
parent::init();
}
public function initContent(){
parent::initContent();
$this->setTemplate(_PS_THEME_DIR_.'paginaejemplo.tpl');
}
public function postProcess(){
if (Tools::isSubmit('submitMessage'))
{
echo "entra o no";
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";
/*$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.
if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from))
$this->errors[] = Tools::displayError('Invalid email address.');
elseif (!$message)
$this->errors[] = Tools::displayError('The message cannot be blank.');
elseif (!Validate::isCleanHtml($message))
$this->errors[] = Tools::displayError('Invalid message');
elseif (!($id_contact = (int)Tools::getValue('id_contact')) || !(Validate::isLoadedObject($contact = new Contact($id_contact, $this->context->language->id))))
$this->errors[] = Tools::displayError('Please select a subject from the list provided. ');
elseif (!empty($file_attachment['name']) && $file_attachment['error'] != 0)
$this->errors[] = Tools::displayError('An error occurred during the file-upload process.');
elseif (!empty($file_attachment['name']) && !in_array(Tools::strtolower(substr($file_attachment['name'], -4)), $extension) && !in_array(Tools::strtolower(substr($file_attachment['name'], -5)), $extension))
$this->errors[] = Tools::displayError('Bad file extension');
else
{
$customer = $this->context->customer;
if (!$customer->id)
$customer->getByEmail($from);
$id_order = (int)$this->getOrder();
if (!((
($id_customer_thread = (int)Tools::getValue('id_customer_thread'))
&& (int)Db::getInstance()->getValue('
SELECT cm.id_customer_thread FROM '._DB_PREFIX_.'customer_thread cm
WHERE cm.id_customer_thread = '.(int)$id_customer_thread.' AND cm.id_shop = '.(int)$this->context->shop->id.' AND token = \''.pSQL(Tools::getValue('token')).'\'')
) || (
$id_customer_thread = CustomerThread::getIdCustomerThreadByEmailAndIdOrder($from, $id_order)
)))
{
$fields = Db::getInstance()->executeS('
SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
FROM '._DB_PREFIX_.'customer_thread cm
WHERE email = \''.pSQL($from).'\' AND cm.id_shop = '.(int)$this->context->shop->id.' AND ('.
($customer->id ? 'id_customer = '.(int)$customer->id.' OR ' : '').'
id_order = '.(int)$id_order.')');
$score = 0;
foreach ($fields as $key => $row)
{
$tmp = 0;
if ((int)$row['id_customer'] && $row['id_customer'] != $customer->id && $row['email'] != $from)
continue;
if ($row['id_order'] != 0 && $id_order != $row['id_order'])
continue;
if ($row['email'] == $from)
$tmp += 4;
if ($row['id_contact'] == $id_contact)
$tmp++;
if (Tools::getValue('id_product') != 0 && $row['id_product'] == Tools::getValue('id_product'))
$tmp += 2;
if ($tmp >= 5 && $tmp >= $score)
{
$score = $tmp;
$id_customer_thread = $row['id_customer_thread'];
}
}
}
$old_message = Db::getInstance()->getValue('
SELECT cm.message FROM '._DB_PREFIX_.'customer_message cm
LEFT JOIN '._DB_PREFIX_.'customer_thread cc on (cm.id_customer_thread = cc.id_customer_thread)
WHERE cc.id_customer_thread = '.(int)$id_customer_thread.' AND cc.id_shop = '.(int)$this->context->shop->id.'
ORDER BY cm.date_add DESC');
if ($old_message == $message)
{
$this->context->smarty->assign('alreadySent', 1);
$contact->email = '';
$contact->customer_service = 0;
}
if ($contact->customer_service)
{
if ((int)$id_customer_thread)
{
$ct = new CustomerThread($id_customer_thread);
$ct->status = 'open';
$ct->id_lang = (int)$this->context->language->id;
$ct->id_contact = (int)$id_contact;
$ct->id_order = (int)$id_order;
if ($id_product = (int)Tools::getValue('id_product'))
$ct->id_product = $id_product;
$ct->update();
}
else
{
$ct = new CustomerThread();
if (isset($customer->id))
$ct->id_customer = (int)$customer->id;
$ct->id_shop = (int)$this->context->shop->id;
$ct->id_order = (int)$id_order;
if ($id_product = (int)Tools::getValue('id_product'))
$ct->id_product = $id_product;
$ct->id_contact = (int)$id_contact;
$ct->id_lang = (int)$this->context->language->id;
$ct->email = $from;
$ct->status = 'open';
$ct->token = Tools::passwdGen(12);
$ct->add();
}
if ($ct->id)
{
$cm = new CustomerMessage();
$cm->id_customer_thread = $ct->id;
$cm->message = $message;
if (isset($file_attachment['rename']) && !empty($file_attachment['rename']) && rename($file_attachment['tmp_name'], _PS_UPLOAD_DIR_.basename($file_attachment['rename'])))
{
$cm->file_name = $file_attachment['rename'];
@chmod(_PS_UPLOAD_DIR_.basename($file_attachment['rename']), 0664);
}
$cm->ip_address = (int)ip2long(Tools::getRemoteAddr());
$cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
if (!$cm->add())
$this->errors[] = Tools::displayError('An error occurred while sending the message.');
}
else
$this->errors[] = Tools::displayError('An error occurred while sending the message.');
}
if (!count($this->errors))
{
$var_list = array(
'{order_name}' => '-',
'{attached_file}' => '-',
'{message}' => Tools::nl2br(stripslashes($message)),
'{email}' => $from,
'{product_name}' => '',
);
if (isset($file_attachment['name']))
$var_list['{attached_file}'] = $file_attachment['name'];
$id_product = (int)Tools::getValue('id_product');
if (isset($ct) && Validate::isLoadedObject($ct) && $ct->id_order)
{
$order = new Order((int)$ct->id_order);
$var_list['{order_name}'] = $order->getUniqReference();
$var_list['{id_order}'] = (int)$order->id;
}
if ($id_product)
{
$product = new Product((int)$id_product);
if (Validate::isLoadedObject($product) && isset($product->name[Context::getContext()->language->id]))
$var_list['{product_name}'] = $product->name[Context::getContext()->language->id];
}
if (empty($contact->email))
Mail::Send($this->context->language->id, 'contact_form', ((isset($ct) && Validate::isLoadedObject($ct)) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent')), $var_list, $from, null, null, null, $file_attachment);
else
{
if (!Mail::Send($this->context->language->id, 'contact', Mail::l('Message from contact form').' [no_sync]',
$var_list, $contact->email, $contact->name, null, null,
$file_attachment, null, _PS_MAIL_DIR_, false, null, null, $from) ||
!Mail::Send($this->context->language->id, 'contact_form', ((isset($ct) && Validate::isLoadedObject($ct)) ? sprintf(Mail::l('Your message has been correctly sent #ct%1$s #tc%2$s'), $ct->id, $ct->token) : Mail::l('Your message has been correctly sent')), $var_list, $from, null, null, null, $file_attachment, null, _PS_MAIL_DIR_, false, null, null, $contact->email))
$this->errors[] = Tools::displayError('An error occurred while sending the message.');
}
}
if (count($this->errors) > 1)
array_unique($this->errors);
elseif (!count($this->errors))
$this->context->smarty->assign('confirmation', 1);
}*/
}
}
}
?>
Con ello llamamos a los estilos y demás para que se integre en la tienda perfectamente.
Dentro del directorio /themes/nombre del tema/ añado el tpl con el siguiente código:
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script language="javascript">// <![CDATA[
$(document).ready(function() {
// Interceptamos el evento submit
$('#contacto').submit(function() {
// Enviamos el formulario usando AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
// Mostramos un mensaje con la respuesta de PHP
success: function(data) {
$('#result').html(data);
}
})
return false;
});
})
// ]]></script>
<script type="text/javascript">
function mostrar(id) {
if (id == "distribucion") {
$("#distribucion").show();
$("#exportacion").hide();
$("#particular").hide();
}
if (id == "exportacion") {
$("#distribucion").hide();
$("#exportacion").show();
$("#particular").hide();
}
if (id == "particular") {
$("#distribucion").hide();
$("#exportacion").hide();
$("#particular").show();
}
}
</script>
</head>
<body>
<h2>Contáctenos</h2>
<p>Si está interesado en nuestros productos solicite información a través del siguiente cuestionario. Seleccionando las diferentes opciones le enviaremos información detallada de la opción que usted elija.</p>
<p><strong>Rellene el siguiente formulario y forme parte de nuestra red de distribuidores:</strong></p>
<form method="post" action="contacto.php" name="contacto" id="contacto">
Seleccione que información desea recibir:
<select onchange="mostrar(this.value);" name="status" id="status">
<option value="">Seleccione una opción</option>
<option value="distribucion">Distribución</option>
<option value="exportacion">Exportación</option>
<option value="particular">Particular</option>
</select>
</form>
<div style="display: none;" class="element" id="distribucion">
<h2>Para distribución</h2>
<form method="post" action="contacto.php" name="contacto" id="contacto">
<table class="table">
<tr>
<td>
<p>Persona de contacto:<br>
<input type="text" name="nombre" class="form-control"></p>
</td>
<td>
<p>Nombre de la empresa / establecimiento:<br>
<input type="text" name="empresa" class="form-control"></p>
</td>
<td>
<p>Tipo de establecimiento:<br>
<input type="text" name="establecimiento" class="form-control"></p>
</td>
</tr>
<tr>
<td>
<p>Teléfono de contacto:<br>
<input type="text" name="telefono" class="form-control"></p>
</td>
<td>
<p>E-mail:<br>
<input type="text" name="email" class="form-control"></p>
</td>
<td>
<p>Ubicación deseada para la distribución:<br>
<select id="ubicacion_distribucion_select" class="form-control">
<option value="">Seleccione una opción</option>
<option value="Local a pie de calle">Local a pie de calle</option>
<option value="Local en centro comercial">Local en centro comercial</option>
<option value="Mercado">Mercado</option>
<option value="Página web">Página web</option>
<option value="Distribución">Distribución</option>
<option value="Otro">Otro</option>
</select>
</p>
</td>
</tr>
<tr>
<td colspan="3">
<p>Comentarios y preguntas:<br>
<textarea class="form-control" rows="5" title="Comentarios y preguntas:" id="comment_fdistribucion" name="comment_fdistribucion"></textarea></p>
</td>
</tr>
</table>
<!--input type="submit" value="Enviar" name="send"-->
<button type="submit" name="submitMessage" id="submitMessage" class="button btn btn-outline button-medium"><span>{l s='Enviar'}</span></button>
</form>
</div>
<div style="display: none;" class="element" id="exportacion">
<h2>Para exportación</h2>
<form method="post" action="contacto.php" name="contacto" id="contacto">
<p>Persona de contacto:<br>
<input type="text" name="nombre" class="form-control"></p>
<p>Nombre de la empresa / establecimiento:<br>
<input type="text" name="empresa" class="form-control"></p>
<p>Tipo de actividad de su empresa:<br>
<input type="text" name="actividad" class="form-control"></p>
<p>Teléfono de contacto:<br>
<input type="text" name="telefono" class="form-control"></p>
<p>E-mail:<br>
<input type="text" name="email" class="form-control"></p>
<p>Área de influencia:<br>
<input type="text" name="influencia" class="form-control"></p>
<p>Comentarios y preguntas:<br>
<textarea class="form-control" rows="5" title="Comentarios y preguntas:" id="comment_fexportacion" name="comment_fexportacion"></textarea></p>
<button type="submit" name="submitMessage" id="submitMessage" class="button btn btn-outline button-medium"><span>{l s='Enviar'}</span></button>
</form>
</div>
<div style="display: none;" class="element" id="particular">
<h2>Si eres particular </h2>
<form method="post" action="contacto.php" name="contacto" id="contacto">
<p>Persona de contacto:<br>
<input type="text" name="nombre" class="form-control"></p>
<p>Teléfono de contacto:<br>
<input type="text" name="telefono" class="form-control"></p>
<p>E-mail:<br>
<input type="text" name="email" class="form-control"></p>
<p>Comentarios y preguntas:<br>
<textarea class="form-control" rows="5" title="Comentarios y preguntas:" id="comment_fparticular" name="comment_fparticular"></textarea></p>
<button type="submit" name="submitMessage" id="submitMessage" class="button btn btn-outline button-medium"><span>{l s='Enviar'}</span></button>
</form>
</div>
<div id="result"> valor</div>
</body></html>
El problema es que no me hace el submit, he probado a poner un alert en un contacto.php externo y sin actualizar la página con ajax y no me funciona. El código fuera de prestashop funciona pero cuando lo integro no, y eso que he añadido el postController al controlador...
¿En qué estoy fallando?
Gracias por la ayuda y vuestro tiempo