Sega063
Интересующийся
Offline
|
|
« : 14-06-2011 09:42 » |
|
Доброго времени суток, у меня такая проблемка, хочу написать модуль на престу, для интернет магазина, что бы мои клиенты могли выбирать время к которому им доставить товар, но вот как его написать, у меня это стало броблемой. Нашёл форму, где они выбирают часы и минуты, но вот как сделать что бы это время записывалось, и привязывалось к каждому клиенту по отдельности и выводилось в админке на заказе. Подскажите пожалуйста, если не трудно по подробнее, я просто ещё новичёк Добавлено через 1 минуту и 1 секунду:вот форма. она наверное подойдёт? <form name="chas" id="chas" size="1"> Выберите время: <select name="language" size="1"> <option selected value="на текущее"> <option value="10 часов">10 часов <option value="11 часов">11 часов </select>
<select name="min" id="min" size="1"> <option value="на текущее" selected> <option value="1">1 минута <option value="2">2 минуты <option value="3">3 минуты <option value="4">4 минут </select> </form> Добавлено через 7 минут и 43 секунды: картинка, что бы наглядно было видно
|
|
« Последнее редактирование: 14-06-2011 13:37 от RXL »
|
Записан
|
|
|
|
Sla
|
|
« Ответ #1 : 14-06-2011 09:59 » |
|
<select name="hours"> <option selected value="на текущее"> <option value="10">10 часов</option> <option value="11">11 часов</option> </select> <select name="min" id="min" size="1"> <option value="-1" selected="selected">на текущее</option> <option value="1">1 минута</option> <option value="2">2 минуты</option> <option value="3">3 минуты</option> <option value="4">4 минут</option> </select>
Может так? Результат запроса на каком языке обрабатывается? Как хранятся данные?
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #2 : 14-06-2011 10:14 » |
|
все данные храняться в базе данных Добавлено через 1 минуту и 26 секунд:Вот код полносстью всей траницы, куда хочу вставить эту форму выбора <script type="text/javascript"> <!-- var baseDir = '{$base_dir_ssl}'; --> </script> <script type="text/javascript" src="{$js_dir}layer.js"></script> <script type="text/javascript" src="{$content_dir}js/conditions.js"></script> {if !$virtual_cart && $giftAllowed && $cart->gift == 1} <script type="text/javascript">{literal} // <![CDATA[ $('document').ready( function(){ $('#gift_div').toggle('slow'); }); //]]> {/literal}</script> {/if} {include file=$tpl_dir./thickbox.tpl}
{capture name=path}{l s='Shipping'}{/capture} {include file=$tpl_dir./breadcrumb.tpl}
<h2>{l s='Shipping'}</h2>
{assign var='current_step' value='shipping'} {include file=$tpl_dir./order-steps.tpl}
{include file=$tpl_dir./errors.tpl}
Выберите время
<select name="hours"> <option selected value="на текущее"> <option value="10">10 часов</option> <option value="11">11 часов</option> </select> <select name="min" id="min" size="1"> <option value="-1" selected="selected">на текущее</option> <option value="1">1 минута</option> <option value="2">2 минуты</option> <option value="3">3 минуты</option> <option value="4">4 минут</option> </select>
{include file=$tpl_dir./errors.tpl}
<form id="form" action="{$base_dir_ssl}order.php" method="post" onsubmit="return acceptCGV('{l s='Please accept the terms of service before the next step.' js=1}');">
{if $conditions} <h3 class="condition_title">{l s='Terms of service'}</h3> <p class="checkbox"> <input type="checkbox" name="cgv" id="cgv" value="1" {if $checkedTOS}checked="checked"{/if} /> <label for="cgv">{l s='I agree with the terms of service and I adhere to them unconditionally.'}</label> <a href="{$link_conditions}" class="thickbox">{l s='(read)'}</a> </p> {/if}
{if $virtual_cart} <input id="input_virtual_carrier" class="hidden" type="hidden" name="id_carrier" value="0" /> {else} <h3 class="carrier_title">{l s='Choose your delivery method'}</h3> {if $recyclablePackAllowed} <p class="checkbox"> <input type="checkbox" name="recyclable" id="recyclable" value="1" {if $recyclable == 1}checked="checked"{/if} /> <label for="recyclable">{l s='I agree to receive my order in recycled packaging'}.</label> </p> {/if}
{if $carriers && count($carriers)} <div class="table_block"><br /> <table class="std"> <thead> <tr> <th class="carrier_action first_item"></th> <th class="carrier_name item">{l s='Carrier'}</th> <th class="carrier_infos item">{l s='Information'}</th> <th class="carrier_price last_item">{l s='Price'}</th> </tr> </thead> <tbody> {foreach from=$carriers item=carrier name=myLoop} <tr class="{if $smarty.foreach.myLoop.first}first_item{elseif $smarty.foreach.myLoop.last}last_item{/if} {if $smarty.foreach.myLoop.index % 2}alternate_item{else}item{/if}"> <td class="carrier_action radio"> <input type="radio" name="id_carrier" value="{$carrier.id_carrier|intval}" id="id_carrier{$carrier.id_carrier|intval}" {if $carrier.id_carrier == $checked || ($checked == 0 && $i == 0) || ($carriers|@sizeof == 1) || $default_carrier == $carrier.id_carrier}checked="checked"{/if} /> </td> <td class="carrier_name"> <label for="id_carrier{$carrier.id_carrier|intval}"> {if $carrier.img}<img src="{$carrier.img|escape:'htmlall':'UTF-8'}" alt="{$carrier.name|escape:'htmlall':'UTF-8'}" />{else}{$carrier.name|escape:'htmlall':'UTF-8'}{/if} </label> </td> <td class="carrier_infos">{$carrier.delay|escape:'htmlall':'UTF-8'}</td> <td class="carrier_price"> {if $carrier.price} <span class="price"> {if $priceDisplay == 1}{convertPrice price=$carrier.price_tax_exc}{else}{convertPrice price=$carrier.price}{/if} </span> {if $use_taxes}{if $priceDisplay == 1} {l s='(tax excl.)'}{else} {l s='(tax incl.)'}{/if}{/if} {else} {l s='Free!'} {/if} </td> </tr> {/foreach} {$HOOK_EXTRACARRIER} </tbody> </table> <div style="display: none;" id="extra_carrier"></div> </div> {else} <p class="warning">{l s='There are no carriers available that will deliver to this address!'}</td></tr> {/if}
{if $giftAllowed} <h3 class="gift_title">{l s='Gift'}</h3> <p class="checkbox"> <input type="checkbox" name="gift" id="gift" value="1" {if $cart->gift == 1}checked="checked"{/if} onclick="$('#gift_div').toggle('slow');" /> <label for="gift">{l s='I would like the order to be gift-wrapped.'}</label> <br /> {if $gift_wrapping_price > 0} ({l s='Additional cost of'} <span class="price"> {if $priceDisplay == 1}{convertPrice price=$total_wrapping_tax_exc}{else}{convertPrice price=$total_wrapping}{/if} </span> {if $use_taxes}{if $priceDisplay == 1} {l s='(tax excl.)'}{else} {l s='(tax incl.)'}{/if}{/if}) {/if} </p> <p id="gift_div" class="textarea"> <label for="gift_message">{l s='If you wish, you can add a note to the gift:'}</label> <textarea rows="5" cols="35" id="gift_message" name="gift_message">{$cart->gift_message|escape:'htmlall':'UTF-8'}</textarea> </p> {/if} {/if}
<p class="cart_navigation submit"> <input type="hidden" name="step" value="3" /> <input type="hidden" name="back" value="{$back}" /> <a href="{$base_dir_ssl}order.php?step=1{if $back}&back={$back}{/if}" title="{l s='Previous'}" class="button">« {l s='Previous'}</a> <input type="submit" name="processCarrier" value="{l s='Next'} »" class="exclusive" /> </p> </form>
|
|
« Последнее редактирование: 14-06-2011 13:37 от RXL »
|
Записан
|
|
|
|
Sla
|
|
« Ответ #3 : 14-06-2011 10:34 » |
|
Это ты показал шаблон, но в шаблоне результат запроса не обрабатывается, нужно показать скрипт обработки запроса
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #4 : 14-06-2011 12:19 » |
|
Тогда вот наверно скрипт обработки: <?php
/* SSL Management */ $useSSL = true;
include_once(dirname(__FILE__).'/config/config.inc.php'); /* Step number is needed on some modules */ $step = intval(Tools::getValue('step')); include_once(dirname(__FILE__).'/init.php');
/* Disable some cache related bugs on the cart/order */ header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
$errors = array();
/* Class FreeOrder to use PaymentModule (abstract class, cannot be instancied) */ class FreeOrder extends PaymentModule {}
/* If some products have disappear */ if (!$cart->checkQuantities()) { $step = 0; $errors[] = Tools::displayError('An item in your cart is no longer available, you cannot proceed with your order'); }
/* Check minimal account */ $orderTotal = $cart->getOrderTotal();
$orderTotalDefaultCurrency = Tools::convertPrice($cart->getOrderTotal(true, 1), Currency::getCurrency(intval(Configuration::get('PS_CURRENCY_DEFAULT')))); $minimalPurchase = floatval(Configuration::get('PS_PURCHASE_MINIMUM')); if ($orderTotalDefaultCurrency < $minimalPurchase) { $step = 0; $errors[] = Tools::displayError('A minimum purchase total of').' '.Tools::displayPrice($minimalPurchase, Currency::getCurrency(intval($cart->id_currency))). ' '.Tools::displayError('is required in order to validate your order'); }
if (!$cookie->isLogged() AND in_array($step, array(1, 2, 3))) Tools::redirect('authentication.php?back=order.php?step='.$step);
$smarty->assign('back', Tools::safeOutput(Tools::getValue('back')));
if ($cart->nbProducts()) { /* Manage discounts */ if ((Tools::isSubmit('submitDiscount') OR Tools::isSubmit('submitDiscount')) AND Tools::getValue('discount_name')) { $discountName = Tools::getValue('discount_name'); if (!Validate::isDiscountName($discountName)) $errors[] = Tools::displayError('voucher name not valid'); else { $discount = new Discount(intval(Discount::getIdByName($discountName))); if (is_object($discount) AND $discount->id) { if ($tmpError = $cart->checkDiscountValidity($discount, $cart->getDiscounts(), $cart->getOrderTotal(), $cart->getProducts(), true)) $errors[] = $tmpError; } else $errors[] = Tools::displayError('voucher name not valid'); if (!sizeof($errors)) { $cart->addDiscount(intval($discount->id)); Tools::redirect('order.php'); } else { $smarty->assign(array( 'errors' => $errors, 'discount_name' => Tools::safeOutput($discountName))); } } } elseif (isset($_GET['deleteDiscount']) AND Validate::isUnsignedId($_GET['deleteDiscount'])) { $cart->deleteDiscount(intval($_GET['deleteDiscount'])); Tools::redirect('order.php'); }
/* Is there only virtual product in cart */ if ($isVirtualCart = $cart->isVirtualCart()) setNoCarrier(); $smarty->assign('virtual_cart', $isVirtualCart);
/* 4 steps to the order */ switch (intval($step)) { case 1: displayAddress(); break; case 2: if(Tools::isSubmit('processAddress')) processAddress(); autoStep(2); displayCarrier(); break; case 3: if(Tools::isSubmit('processCarrier')) processCarrier(); autoStep(3); checkFreeOrder(); displayPayment(); break; default: $smarty->assign('errors', $errors); displaySummary(); break; } } else { /* Default page */ $smarty->assign('empty', 1); Tools::safePostVars(); include_once(dirname(__FILE__).'/header.php'); $smarty->display(_PS_THEME_DIR_.'shopping-cart.tpl'); }
include(dirname(__FILE__).'/footer.php');
/* Order process controller */ function autoStep($step) { global $cart, $isVirtualCart;
if ($step >= 2 AND (!$cart->id_address_delivery OR !$cart->id_address_invoice)) Tools::redirect('order.php?step=1'); $delivery = new Address(intval($cart->id_address_delivery)); $invoice = new Address(intval($cart->id_address_invoice)); if ($delivery->deleted OR $invoice->deleted) { if ($delivery->deleted) unset($cart->id_address_delivery); if ($invoice->deleted) unset($cart->id_address_invoice); Tools::redirect('order.php?step=1'); } elseif ($step >= 3 AND !$cart->id_carrier AND !$isVirtualCart) Tools::redirect('order.php?step=2'); }
/* Bypass payment step if total is 0 */ function checkFreeOrder() { global $cart;
if ($cart->getOrderTotal() <= 0) { $order = new FreeOrder(); $order->validateOrder(intval($cart->id), _PS_OS_PAYMENT_, 0, Tools::displayError('Free order', false)); Tools::redirect('history.php'); } }
/** * Set id_carrier to 0 (no shipping price) * */ function setNoCarrier() { global $cart; $cart->id_carrier = 0; $cart->update(); }
/* * Manage address */ function processAddress() { global $cart, $smarty; $errors = array();
if (!isset($_POST['id_address_delivery']) OR !Address::isCountryActiveById(intval($_POST['id_address_delivery']))) $errors[] = 'this address is not in a valid area'; else { $cart->id_address_delivery = intval(Tools::getValue('id_address_delivery')); $cart->id_address_invoice = Tools::isSubmit('same') ? $cart->id_address_delivery : intval(Tools::getValue('id_address_invoice')); if (!$cart->update()) $errors[] = Tools::displayError('an error occured while updating your cart');
if (Tools::isSubmit('message') AND !empty($_POST['message'])) { if (!Validate::isMessage($_POST['message'])) $errors[] = Tools::displayError('invalid message'); elseif ($oldMessage = Message::getMessageByCartId(intval($cart->id))) { $message = new Message(intval($oldMessage['id_message'])); $message->message = htmlentities($_POST['message'], ENT_COMPAT, 'UTF-8'); $message->update(); } else { $message = new Message(); $message->message = htmlentities($_POST['message'], ENT_COMPAT, 'UTF-8'); $message->id_cart = intval($cart->id); $message->id_customer = intval($cart->id_customer); $message->add(); } } } if (sizeof($errors)) { if (Tools::getValue('ajax')) die('{\'hasError\' : true, errors : [\''.implode('\',\'', $errors).'\']}'); $smarty->assign('errors', $errors); displayAddress(); include_once(dirname(__FILE__).'/footer.php'); exit; } if (Tools::getValue('ajax')) die(true); }
/* Carrier step */ function processCarrier() { global $cart, $smarty, $isVirtualCart, $orderTotal;
$errors = array();
$cart->recyclable = (isset($_POST['recyclable']) AND !empty($_POST['recyclable'])) ? 1 : 0;
if (isset($_POST['gift']) AND !empty($_POST['gift'])) { if (!Validate::isMessage($_POST['gift_message'])) $errors[] = Tools::displayError('invalid gift message'); else { $cart->gift = 1; $cart->gift_message = strip_tags($_POST['gift_message']); } } else $cart->gift = 0;
$address = new Address(intval($cart->id_address_delivery)); if (!Validate::isLoadedObject($address)) die(Tools::displayError()); if (!$id_zone = Address::getZoneById($address->id)) $errors[] = Tools::displayError('no zone match with your address'); if (isset($_POST['id_carrier']) AND Validate::isInt($_POST['id_carrier']) AND sizeof(Carrier::checkCarrierZone(intval($_POST['id_carrier']), intval($id_zone)))) $cart->id_carrier = intval($_POST['id_carrier']); elseif (!$isVirtualCart) $errors[] = Tools::displayError('invalid carrier or no carrier selected');
$cart->update();
if (sizeof($errors)) { $smarty->assign('errors', $errors); displayCarrier(); include(dirname(__FILE__).'/footer.php'); exit; } $orderTotal = $cart->getOrderTotal(); }
/* Address step */ function displayAddress() { global $smarty, $cookie, $cart;
if (!Customer::getAddressesTotalById(intval($cookie->id_customer))) Tools::redirect('address.php?back=order.php?step=1'); $customer = new Customer(intval($cookie->id_customer)); if (Validate::isLoadedObject($customer)) { /* Getting customer addresses */ $customerAddresses = $customer->getAddresses(intval($cookie->id_lang)); $smarty->assign('addresses', $customerAddresses);
/* Setting default addresses for cart */ if ((!isset($cart->id_address_delivery) OR empty($cart->id_address_delivery)) AND sizeof($customerAddresses)) { $cart->id_address_delivery = intval($customerAddresses[0]['id_address']); $update = 1; } if ((!isset($cart->id_address_invoice) OR empty($cart->id_address_invoice)) AND sizeof($customerAddresses)) { $cart->id_address_invoice = intval($customerAddresses[0]['id_address']); $update = 1; } /* Update cart addresses only if needed */ if (isset($update) AND $update) $cart->update();
/* If delivery address is valid in cart, assign it to Smarty */ if (isset($cart->id_address_delivery)) { $deliveryAddress = new Address(intval($cart->id_address_delivery)); if (Validate::isLoadedObject($deliveryAddress) AND ($deliveryAddress->id_customer == $customer->id)) $smarty->assign('delivery', $deliveryAddress); }
/* If invoice address is valid in cart, assign it to Smarty */ if (isset($cart->id_address_invoice)) { $invoiceAddress = new Address(intval($cart->id_address_invoice)); if (Validate::isLoadedObject($invoiceAddress) AND ($invoiceAddress->id_customer == $customer->id)) $smarty->assign('invoice', $invoiceAddress); } } if ($oldMessage = Message::getMessageByCartId(intval($cart->id))) $smarty->assign('oldMessage', $oldMessage['message']); $smarty->assign('cart', $cart);
Tools::safePostVars(); include_once(dirname(__FILE__).'/header.php'); $smarty->display(_PS_THEME_DIR_.'order-address.tpl'); }
/* Carrier step */ function displayCarrier() { global $smarty, $cart, $cookie, $defaultCountry, $link;
$address = new Address(intval($cart->id_address_delivery)); $id_zone = Address::getZoneById(intval($address->id)); if (isset($cookie->id_customer)) $customer = new Customer(intval($cookie->id_customer)); else die(Tools::displayError($this->l('Hack attempt: No customer'))); $result = Carrier::getCarriers(intval($cookie->id_lang), true, false, intval($id_zone), $customer->getGroups()); if (!$result) $result = Carrier::getCarriers(intval($cookie->id_lang), true, false, intval($id_zone)); $resultsArray = array(); foreach ($result AS $k => $row) { $carrier = new Carrier(intval($row['id_carrier']));
// Get only carriers that are compliant with shipping method if ((Configuration::get('PS_SHIPPING_METHOD') AND $carrier->getMaxDeliveryPriceByWeight($id_zone) === false) OR (!Configuration::get('PS_SHIPPING_METHOD') AND $carrier->getMaxDeliveryPriceByPrice($id_zone) === false)) { unset($result[$k]); continue ; } // If out-of-range behavior carrier is set on "Desactivate carrier" if ($row['range_behavior']) { // Get id zone if (isset($cart->id_address_delivery) AND $cart->id_address_delivery) $id_zone = Address::getZoneById(intval($cart->id_address_delivery)); else $id_zone = intval($defaultCountry->id_zone);
// Get only carriers that have a range compatible with cart if ((Configuration::get('PS_SHIPPING_METHOD') AND (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone))) OR (!Configuration::get('PS_SHIPPING_METHOD') AND (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, 4), $id_zone)))) { unset($result[$k]); continue ; } } $row['name'] = (strval($row['name']) != '0' ? $row['name'] : Configuration::get('PS_SHOP_NAME')); $row['price'] = $cart->getOrderShippingCost(intval($row['id_carrier'])); $row['price_tax_exc'] = $cart->getOrderShippingCost(intval($row['id_carrier']), false); $row['img'] = file_exists(_PS_SHIP_IMG_DIR_.intval($row['id_carrier']).'.jpg') ? _THEME_SHIP_DIR_.intval($row['id_carrier']).'.jpg' : ''; $resultsArray[] = $row; }
// Wrapping fees $wrapping_fees = floatval(Configuration::get('PS_GIFT_WRAPPING_PRICE')); $wrapping_fees_tax = new Tax(intval(Configuration::get('PS_GIFT_WRAPPING_TAX'))); $wrapping_fees_tax_inc = $wrapping_fees * (1 + ((floatval($wrapping_fees_tax->rate) / 100)));
if (Validate::isUnsignedInt($cart->id_carrier) AND $cart->id_carrier) { $carrier = new Carrier(intval($cart->id_carrier)); if ($carrier->active AND !$carrier->deleted) $checked = intval($cart->id_carrier); } $cms = new CMS(3, intval($cookie->id_lang)); $link_conditions = $link->getCMSLink($cms, $cms->link_rewrite); if (!strpos($link_conditions, '?')) $link_conditions .= '?content_only=1&TB_iframe=true&width=450&height=500&thickbox=true'; else $link_conditions .= '&content_only=1&TB_iframe=true&width=450&height=500&thickbox=true'; if (!isset($checked) OR intval($checked) == 0) $checked = intval(Configuration::get('PS_CARRIER_DEFAULT')); $smarty->assign(array( 'checkedTOS' => intval($cookie->checkedTOS), 'recyclablePackAllowed' => intval(Configuration::get('PS_RECYCLABLE_PACK')), 'giftAllowed' => intval(Configuration::get('PS_GIFT_WRAPPING')), 'conditions' => intval(Configuration::get('PS_CONDITIONS')), 'link_conditions' => $link_conditions, 'recyclable' => intval($cart->recyclable), 'gift_wrapping_price' => floatval(Configuration::get('PS_GIFT_WRAPPING_PRICE')), 'carriers' => $resultsArray, 'default_carrier' => intval(Configuration::get('PS_CARRIER_DEFAULT')), 'HOOK_EXTRACARRIER' => Module::hookExec('extraCarrier', array('address' => $address)), 'checked' => intval($checked), 'total_wrapping' => Tools::convertPrice($wrapping_fees_tax_inc, new Currency(intval($cookie->id_currency))), 'total_wrapping_tax_exc' => Tools::convertPrice($wrapping_fees, new Currency(intval($cookie->id_currency))))); Tools::safePostVars(); $css_files = array(__PS_BASE_URI__.'css/thickbox.css' => 'all'); $js_files = array(__PS_BASE_URI__.'js/jquery/thickbox-modified.js'); include_once(dirname(__FILE__).'/header.php'); $smarty->display(_PS_THEME_DIR_.'order-carrier.tpl'); }
/* Payment step */ function displayPayment() { global $smarty, $cart, $currency, $cookie, $orderTotal;
// Redirect instead of displaying payment modules if any module are grefted on Hook::backBeforePayment(strval(Tools::getValue('back')));
/* We may need to display an order summary */ $smarty->assign($cart->getSummaryDetails());
$cookie->checkedTOS = '1'; $smarty->assign(array( 'HOOK_PAYMENT' => Module::hookExecPayment(), 'total_price' => floatval($orderTotal), 'taxes_enabled' => intval(Configuration::get('PS_TAX')) ));
Tools::safePostVars(); include_once(dirname(__FILE__).'/header.php'); $smarty->display(_PS_THEME_DIR_.'order-payment.tpl'); }
/* Confirmation step */ function displaySummary() { global $smarty, $cart;
if (file_exists(_PS_SHIP_IMG_DIR_.intval($cart->id_carrier).'.jpg')) $smarty->assign('carrierPicture', 1); $summary = $cart->getSummaryDetails(); $customizedDatas = Product::getAllCustomizedDatas(intval($cart->id)); Product::addCustomizationPrice($summary['products'], $customizedDatas);
if ($free_ship = Tools::convertPrice(floatval(Configuration::get('PS_SHIPPING_FREE_PRICE')), new Currency(intval($cart->id_currency)))) { $discounts = $cart->getDiscounts(); $total_free_ship = $free_ship - ($summary['total_products_wt'] + $summary['total_discounts']); foreach ($discounts as $discount) if ($discount['id_discount_type'] == 3) { $total_free_ship = 0; break ; } $smarty->assign('free_ship', $total_free_ship); } // for compatibility with 1.2 themes foreach($summary['products'] AS $key => $product) $summary['products'][$key]['quantity'] = $product['cart_quantity']; $smarty->assign($summary); $token = Tools::getToken(false); $smarty->assign(array( 'token_cart' => $token, 'isVirtualCart' => $cart->isVirtualCart(), 'productNumber' => $cart->nbProducts(), 'voucherAllowed' => Configuration::get('PS_VOUCHERS'), 'HOOK_SHOPPING_CART' => Module::hookExec('shoppingCart', $summary), 'HOOK_SHOPPING_CART_EXTRA' => Module::hookExec('shoppingCartExtra', $summary), 'shippingCost' => $cart->getOrderTotal(true, 5), 'shippingCostTaxExc' => $cart->getOrderTotal(false, 5), 'customizedDatas' => $customizedDatas, 'CUSTOMIZE_FILE' => _CUSTOMIZE_FILE_, 'CUSTOMIZE_TEXTFIELD' => _CUSTOMIZE_TEXTFIELD_, 'lastProductAdded' => $cart->getLastProduct() )); Tools::safePostVars(); include_once(dirname(__FILE__).'/header.php'); $smarty->display(_PS_THEME_DIR_.'shopping-cart.tpl'); }
?>
|
|
« Последнее редактирование: 14-06-2011 13:36 от RXL »
|
Записан
|
|
|
|
RXL
Технический
Администратор
Offline
Пол:
|
|
« Ответ #5 : 14-06-2011 13:25 » |
|
Sega063, пользуйся тегами [code] ... [/code] ! А то последуют кары. Это ж читать невозможно.
|
|
|
Записан
|
... мы преодолеваем эту трудность без синтеза распределенных прототипов. (с) Жуков М.С.
|
|
|
Sla
|
|
« Ответ #6 : 14-06-2011 14:13 » |
|
Sega063, ты не то показываешь, зачем мне твой index.php? В каком скрипте (части скрипта) происходит обработка запроса?
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #7 : 14-06-2011 14:26 » |
|
обработка кода? Т.е. это то, где написанно действие, когда нажимаешь на кнопку, правильно? или я ошибаюсь? Просто я новичёк и заранее прошу прощния за тупые вопросы Добавлено через 8 минут и 21 секунду:Вроде бы нашёл, наверно это <?php
/** * Orders class, Order.php * Orders management * @category classes * * @author PrestaShop <support@prestashop.com> * @copyright PrestaShop * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0 * @version 1.3 * */
class Order extends ObjectModel { /** @var integer Delivery address id */ public $id_address_delivery;
/** @var integer Invoice address id */ public $id_address_invoice;
/** @var integer Cart id */ public $id_cart;
/** @var integer Currency id */ public $id_currency;
/** @var integer Language id */ public $id_lang;
/** @var integer Customer id */ public $id_customer;
/** @var integer Carrier id */ public $id_carrier;
/** @var string Secure key */ public $secure_key;
/** @var string Payment method id */ public $payment;
/** @var string Payment module */ public $module;
/** @var boolean Customer is ok for a recyclable package */ public $recyclable = 1;
/** @var boolean True if the customer wants a gift wrapping */ public $gift = 0;
/** @var string Gift message if specified */ public $gift_message;
/** @var string Shipping number */ public $shipping_number;
/** @var float Discounts total */ public $total_discounts;
/** @var float Total to pay */ public $total_paid;
/** @var float Total really paid */ public $total_paid_real;
/** @var float Products total */ public $total_products;
/** @var float Products total tax excluded */ public $total_products_wt;
/** @var float Shipping total */ public $total_shipping; /** @var float Wrapping total */ public $total_wrapping;
/** @var integer Invoice number */ public $invoice_number; /** @var integer Delivery number */ public $delivery_number; /** @var string Invoice creation date */ public $invoice_date; /** @var string Delivery creation date */ public $delivery_date; /** @var boolean Order validity (paid and not canceled) */ public $valid; /** @var string Object creation date */ public $date_add;
/** @var string Object last modification date */ public $date_upd;
protected $tables = array ('orders');
protected $fieldsRequired = array('id_address_delivery', 'id_address_invoice', 'id_cart', 'id_currency', 'id_lang', 'id_customer', 'id_carrier', 'payment', 'total_paid', 'total_paid_real', 'total_products', 'total_products_wt'); protected $fieldsSize = array('payment' => 32); protected $fieldsValidate = array( 'id_address_delivery' => 'isUnsignedId', 'id_address_invoice' => 'isUnsignedId', 'id_cart' => 'isUnsignedId', 'id_currency' => 'isUnsignedId', 'id_lang' => 'isUnsignedId', 'id_customer' => 'isUnsignedId', 'id_carrier' => 'isUnsignedId', 'secure_key' => 'isMd5', 'payment' => 'isGenericName', 'recyclable' => 'isBool', 'gift' => 'isBool', 'gift_message' => 'isMessage', 'total_discounts' => 'isPrice', 'total_paid' => 'isPrice', 'total_paid_real' => 'isPrice', 'total_products' => 'isPrice', 'total_products_wt' => 'isPrice', 'total_shipping' => 'isPrice', 'total_wrapping' => 'isPrice', 'shipping_number' => 'isUrl' );
/* MySQL does not allow 'order' for a table name */ protected $table = 'orders'; protected $identifier = 'id_order'; private $_taxCalculationMethod = PS_TAX_EXC;
public function getFields() { parent::validateFields();
$fields['id_address_delivery'] = intval($this->id_address_delivery); $fields['id_address_invoice'] = intval($this->id_address_invoice); $fields['id_cart'] = intval($this->id_cart); $fields['id_currency'] = intval($this->id_currency); $fields['id_lang'] = intval($this->id_lang); $fields['id_customer'] = intval($this->id_customer); $fields['id_carrier'] = intval($this->id_carrier); $fields['secure_key'] = pSQL($this->secure_key); $fields['payment'] = pSQL($this->payment); $fields['module'] = pSQL($this->module); $fields['recyclable'] = intval($this->recyclable); $fields['gift'] = intval($this->gift); $fields['gift_message'] = pSQL($this->gift_message); $fields['shipping_number'] = pSQL($this->shipping_number); $fields['total_discounts'] = floatval($this->total_discounts); $fields['total_paid'] = floatval($this->total_paid); $fields['total_paid_real'] = floatval($this->total_paid_real); $fields['total_products'] = floatval($this->total_products); $fields['total_products_wt'] = floatval($this->total_products_wt); $fields['total_shipping'] = floatval($this->total_shipping); $fields['total_wrapping'] = floatval($this->total_wrapping); $fields['invoice_number'] = intval($this->invoice_number); $fields['delivery_number'] = intval($this->delivery_number); $fields['invoice_date'] = pSQL($this->invoice_date); $fields['delivery_date'] = pSQL($this->delivery_date); $fields['valid'] = intval($this->valid) ? 1 : 0; $fields['date_add'] = pSQL($this->date_add); $fields['date_upd'] = pSQL($this->date_upd);
return $fields; }
public function __construct($id = NULL, $id_lang = NULL) { parent::__construct($id, $id_lang); if ($this->id_customer) { $customer = new Customer(intval($this->id_customer)); $this->_taxCalculationMethod = Group::getPriceDisplayMethod(intval($customer->id_default_group)); } else $this->_taxCalculationMethod = Group::getDefaultPriceDisplayMethod(); }
public function getTaxCalculationMethod() { return intval($this->_taxCalculationMethod); }
/* Does NOT delete a product but "cancel" it (which means return/refund/delete it depending of the case) */ public function deleteProduct($order, $orderDetail, $quantity) { if (!$currentStatus = intval($this->getCurrentState())) return false;
if ($this->hasBeenDelivered()) { if (!Configuration::get('PS_ORDER_RETURN')) die(Tools::displayError()); $orderDetail->product_quantity_return += intval($quantity); return $orderDetail->update(); } elseif ($this->hasBeenPaid()) { $orderDetail->product_quantity_refunded += intval($quantity); return $orderDetail->update(); } return $this->_deleteProduct($orderDetail, intval($quantity)); }
/* DOES delete the product */ private function _deleteProduct($orderDetail, $quantity) { $unitPrice = number_format($orderDetail->product_price * (1 + $orderDetail->tax_rate * 0.01), 2, '.', ''); $productPrice = number_format($quantity * $unitPrice, 2, '.', ''); $productPriceWithoutTax = number_format($productPrice / (1 + $orderDetail->tax_rate * 0.01), 2, '.', '');
/* Update order */ $this->total_paid -= $productPrice; $this->total_paid_real -= $productPrice; $this->total_products -= $productPriceWithoutTax; $this->total_products_wt -= $productPrice; /* Prevent from floating precision issues (total_products has only 2 decimals) */ if ($this->total_products < 0) $this->total_products = 0; /* Prevent from floating precision issues */ $this->total_paid = number_format($this->total_paid, 2, '.', ''); $this->total_paid_real = number_format($this->total_paid_real, 2, '.', ''); $this->total_products = number_format($this->total_products, 2, '.', ''); $this->total_products_wt = number_format($this->total_products_wt, 2, '.', '');
/* Update order detail */ $orderDetail->product_quantity -= intval($quantity); if (!$orderDetail->product_quantity) { if (!$orderDetail->delete()) return false; if (count($this->getProductsDetail()) == 0) { global $cookie; $history = new OrderHistory(); $history->id_order = intval($this->id); $history->changeIdOrderState(_PS_OS_CANCELED_, intval($this->id)); if (!$history->addWithemail()) return false; } return $this->update(); } return $orderDetail->update() AND $this->update(); }
public function deleteCustomization($id_customization, $quantity, $orderDetail) { if (!$currentStatus = intval($this->getCurrentState())) return false;
if ($this->hasBeenDelivered()) return Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'customization` SET `quantity_returned` = `quantity_returned` + '.intval($quantity).' WHERE `id_customization` = '.intval($id_customization).' AND `id_cart` = '.intval($this->id_cart).' AND `id_product` = '.intval($orderDetail->product_id)); elseif ($this->hasBeenPaid()) return Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'customization` SET `quantity_refunded` = `quantity_refunded` + '.intval($quantity).' WHERE `id_customization` = '.intval($id_customization).' AND `id_cart` = '.intval($this->id_cart).' AND `id_product` = '.intval($orderDetail->product_id)); if (!Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'customization` SET `quantity` = `quantity` - '.intval($quantity).' WHERE `id_customization` = '.intval($id_customization).' AND `id_cart` = '.intval($this->id_cart).' AND `id_product` = '.intval($orderDetail->product_id))) return false; if (!Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'customization` WHERE `quantity` = 0')) return false; return $this->_deleteProduct($orderDetail, intval($quantity)); }
/** * Get order history * * @param integer $id_lang Language id * * @return array History entries ordered by date DESC */ public function getHistory($id_lang, $id_order_state = false, $no_hidden = false) { $id_lang = $id_lang ? intval($id_lang) : 'o.`id_lang`'; $query = ' SELECT oh.*, e.`firstname` AS employee_firstname, e.`lastname` AS employee_lastname, osl.`name` AS ostate_name FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_history` oh ON o.`id_order` = oh.`id_order` LEFT JOIN `'._DB_PREFIX_.'order_state` os ON os.`id_order_state` = oh.`id_order_state` LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.intval($id_lang).') LEFT JOIN `'._DB_PREFIX_.'employee` e ON e.`id_employee` = oh.`id_employee` WHERE oh.id_order = '.intval($this->id).' '.($no_hidden ? ' AND os.hidden = 0' : ''); if (intval($id_order_state)) $query.= ' AND oh.`id_order_state` = '.intval($id_order_state); $query.= ' ORDER BY oh.date_add DESC, oh.id_order_history DESC'; return Db::getInstance()->ExecuteS($query); }
public function getProductsDetail() { return Db::getInstance()->ExecuteS(' SELECT * FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = '.intval($this->id)); } public function getLastMessage() { $sql = 'SELECT `message` FROM `'._DB_PREFIX_.'message` WHERE `id_order` = '.intval($this->id).' ORDER BY `id_message` desc'; $result = Db::getInstance()->getRow($sql); return $result['message']; }
public function getFirstMessage() { $sql = 'SELECT `message` FROM `'._DB_PREFIX_.'message` WHERE `id_order` = '.intval($this->id).' ORDER BY `id_message` asc'; $result = Db::getInstance()->getRow($sql); return $result['message']; }
/** * Get order products * * @return array Products with price, quantity (with taxe and without) */ public function getProducts($products = false, $selectedProducts = false, $selectedQty = false) { if (!$products) $products = $this->getProductsDetail(); $resultArray = array(); foreach ($products AS $k => $row) { // Change qty if selected if ($selectedQty) { $row['product_quantity'] = 0; foreach ($selectedProducts AS $key => $id_product) if ($row['id_order_detail'] == $id_product) $row['product_quantity'] = intval($selectedQty[$key]); if (!$row['product_quantity']) continue ; } $price = $row['product_price']; if ($this->_taxCalculationMethod == PS_TAX_EXC) $price = Tools::ps_round($price, 2); $row['product_price_wt'] = Tools::ps_round($price * (1 + ($row['tax_rate'] * 0.01)), 2); $row['total_wt'] = $row['product_quantity'] * $row['product_price_wt']; $row['total_price'] = $row['product_quantity'] * $row['product_price_wt'];
/* Add information for virtual product */ if ($row['download_hash'] AND !empty($row['download_hash'])) $row['filename'] = ProductDownload::getFilenameFromIdProduct($row['product_id']);
/* Stock product */ $resultArray[intval($row['id_order_detail'])] = $row; } return $resultArray; }
/** * Count virtual products in order * * @return int number of virtual products */ public function getVirtualProducts() { $sql = ' SELECT `product_id`, `download_hash`, `download_deadline` FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = '.intval($this->id).' AND `download_hash` <> \'\''; return Db::getInstance()->ExecuteS($sql); }
/** * Check if order contains (only) virtual products * @return boolean true if is a virtual order or false * */ public function isVirtual($strict = true) { $products = $this->getProducts(); if (count($products) < 1) return false; $virtual = false; foreach ($products AS $product) { $pd = ProductDownload::getIdFromIdProduct(intval($product['product_id'])); if ($pd AND Validate::isUnsignedInt($pd) AND $product['download_hash']) { if ($strict === false) return true; $virtual &= true; } } return $virtual; }
/** * Get order discounts * * @return array Discounts with price and quantity */ public function getDiscounts() { return Db::getInstance()->ExecuteS(' SELECT * FROM `'._DB_PREFIX_.'order_discount` WHERE `id_order` = '.intval($this->id)); }
static public function getDiscountsCustomer($id_customer, $id_discount) { $result = Db::getInstance()->ExecuteS(' SELECT od.id_discount FROM `'._DB_PREFIX_.'orders` o LEFT JOIN '._DB_PREFIX_.'order_discount od ON (od.id_order = o.id_order) WHERE o.id_customer = '.intval($id_customer).' AND od.id_discount = '.intval($id_discount));
return Db::getInstance()->NumRows(); }
/** * Get current order state (eg. Awaiting payment, Delivered...) * * @return array Order state details */ public function getCurrentState() { $orderHistory = OrderHistory::getLastOrderState($this->id); if (!isset($orderHistory) OR !$orderHistory) return false; return $orderHistory->id; }
/** * Get current order state name (eg. Awaiting payment, Delivered...) * * @return array Order state details */ public function getCurrentStateFull($id_lang) { return Db::getInstance()->getRow(' SELECT oh.`id_order_state`, osl.`name`, os.`logable` FROM `'._DB_PREFIX_.'order_history` oh LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (osl.`id_order_state` = oh.`id_order_state`) LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = oh.`id_order_state`) WHERE osl.`id_lang` = '.intval($id_lang).' AND oh.`id_order` = '.intval($this->id).' ORDER BY `date_add` DESC, `id_order_history` DESC'); }
public function isLogable() { return $this->valid; } public function hasBeenDelivered() { return sizeof($this->getHistory(intval($this->id_lang), _PS_OS_DELIVERED_)); } public function hasBeenPaid() { return sizeof($this->getHistory(intval($this->id_lang), _PS_OS_PAYMENT_)); }
public function hasBeenShipped() { return sizeof($this->getHistory(intval($this->id_lang), _PS_OS_SHIPPING_)); }
public function isInPreparation() { return sizeof($this->getHistory(intval($this->id_lang), _PS_OS_PREPARATION_)); }
/** * Get customer orders * * @param integer $id_customer Customer id * @return array Customer orders */ static public function getCustomerOrders($id_customer) { global $cookie; $res = Db::getInstance()->ExecuteS(' SELECT o.*, ( SELECT SUM(od.`product_quantity`) FROM `'._DB_PREFIX_.'order_detail` od WHERE od.`id_order` = o.`id_order`) AS nb_products FROM `'._DB_PREFIX_.'orders` o LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON (od.`id_order` = o.`id_order`) WHERE o.`id_customer` = '.intval($id_customer).' GROUP BY o.`id_order` ORDER BY o.`date_add` DESC'); if (!$res) return array();
foreach ($res AS $key => $val) { $res2 = Db::getInstance()->ExecuteS(' SELECT os.`id_order_state`, osl.`name` AS order_state, os.`invoice` FROM `'._DB_PREFIX_.'order_history` oh LEFT JOIN `'._DB_PREFIX_.'order_state` os ON (os.`id_order_state` = oh.`id_order_state`) INNER JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.intval($cookie->id_lang).') WHERE oh.`id_order` = '.intval($val['id_order']).' AND os.`hidden` != 1 ORDER BY oh.`date_add` DESC LIMIT 1 '); if ($res2) $res[$key] = array_merge($res[$key], $res2[0]); } return $res; }
static public function getOrdersIdByDate($date_from, $date_to, $id_customer = NULL, $type = NULL) { $sql = ' SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE DATE_ADD(date_upd, INTERVAL -1 DAY) <= \''.pSQL($date_to).'\' AND date_upd >= \''.pSQL($date_from).'\'' .($type ? ' AND '.pSQL(strval($type)).'_number != 0' : '') .($id_customer ? ' AND id_customer = '.intval($id_customer) : ''); $result = Db::getInstance()->ExecuteS($sql);
$orders = array(); foreach ($result AS $order) $orders[] = intval($order['id_order']); return $orders; }
static public function getOrdersIdInvoiceByDate($date_from, $date_to, $id_customer = NULL, $type = NULL) { $result = Db::getInstance()->ExecuteS(' SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE DATE_ADD(invoice_date, INTERVAL -1 DAY) <= \''.pSQL($date_to).'\' AND invoice_date >= \''.pSQL($date_from).'\'' .($type ? ' AND '.pSQL(strval($type)).'_number != 0' : '') .($id_customer ? ' AND id_customer = '.intval($id_customer) : ''). ' ORDER BY invoice_date ASC');
$orders = array(); foreach ($result AS $order) $orders[] = intval($order['id_order']); return $orders; }
/** * Get product total without taxes * * @return Product total with taxes */ public function getTotalProductsWithoutTaxes($products = false) { return $this->total_products; }
/** * Get product total with taxes * * @return Product total with taxes */ public function getTotalProductsWithTaxes($products = false) { if ($this->total_products_wt != '0.00' AND !$products) return $this->total_products_wt;
if (!$products) $products = $this->getProductsDetail();
$total = 0; foreach ($products AS $k => $row) { $qty = intval($row['product_quantity']); $total += floatval($row['product_price']) * $qty * (1 + $row['tax_rate'] / 100); } $this->total_products_wt = round($total, 2); $this->update(); return $this->total_products_wt; }
/** * Get customer orders number * * @param integer $id_customer Customer id * @return array Customer orders number */ static public function getCustomerNbOrders($id_customer) { $result = Db::getInstance()->getRow(' SELECT COUNT(`id_order`) AS nb FROM `'._DB_PREFIX_.'orders` WHERE `id_customer` = '.intval($id_customer));
return isset($result['nb']) ? $result['nb'] : 0; }
/** * Get an order by its cart id * * @param integer $id_cart Cart id * @return array Order details */ static public function getOrderByCartId($id_cart) { $result = Db::getInstance()->getRow(' SELECT `id_order` FROM `'._DB_PREFIX_.'orders` WHERE `id_cart` = '.intval($id_cart));
return isset($result['id_order']) ? $result['id_order'] : false; }
/** * Add a discount to order * * @param integer $id_discount Discount id * @param string $name Discount name * @param float $value Discount value * @return boolean Query sucess or not */ public function addDiscount($id_discount, $name, $value) { return Db::getInstance()->AutoExecute(_DB_PREFIX_.'order_discount', array('id_order' => intval($this->id), 'id_discount' => intval($id_discount), 'name' => pSQL($name), 'value' => floatval($value)), 'INSERT'); }
/** * Get orders number last week * * @return integer Orders number last week */ public static function getWeeklyOrders() { $result = Db::getInstance()->getRow(' SELECT COUNT(`id_order`) as nb FROM `'._DB_PREFIX_.'orders` WHERE YEARWEEK(`date_add`) = YEARWEEK(NOW())');
return isset($result['nb']) ? $result['nb'] : 0; }
/** * Get sales amount last month * * @return float Sales amount last month */ public static function getMonthlySales() { $result = Db::getInstance()->getRow(' SELECT SUM(`total_paid`) as nb FROM `'._DB_PREFIX_.'orders` WHERE MONTH(`date_add`) = MONTH(NOW()) AND YEAR(`date_add`) = YEAR(NOW())');
return isset($result['nb']) ? $result['nb'] : 0; }
public function getNumberOfDays() { $nbReturnDays = intval(Configuration::get('PS_ORDER_RETURN_NB_DAYS')); if (!$nbReturnDays) return true; $result = Db::getInstance()->getRow(' SELECT TO_DAYS(NOW()) - TO_DAYS(`delivery_date`) AS days FROM `'._DB_PREFIX_.'orders` WHERE `id_order` = '.intval($this->id)); if ($result['days'] <= $nbReturnDays) return true; return false; }
public function isReturnable() { return (intval(Configuration::get('PS_ORDER_RETURN')) == 1 AND intval($this->getCurrentState()) == _PS_OS_DELIVERED_ AND $this->getNumberOfDays()); }
public function setInvoice() { // Set invoice number $number = intval(Configuration::get('PS_INVOICE_NUMBER')); if (!intval($number)) die(Tools::displayError('Invalid invoice number')); $this->invoice_number = $number; Configuration::updateValue('PS_INVOICE_NUMBER', $number + 1);
// Set invoice date $this->invoice_date = date('Y-m-d H:i:s'); // Save $this->update(); }
public function setDelivery() { // Set delivery number $number = intval(Configuration::get('PS_DELIVERY_NUMBER')); if (!intval($number)) die(Tools::displayError('Invalid delivery number')); $this->delivery_number = $number; Configuration::updateValue('PS_DELIVERY_NUMBER', $number + 1);
// Set delivery date $this->delivery_date = date('Y-m-d H:i:s'); // Update object $this->update(); } static public function printPDFIcons($id_order, $tr) { $order = new Order($id_order); $orderState = OrderHistory::getLastOrderState($id_order); if (!Validate::isLoadedObject($orderState) OR !Validate::isLoadedObject($order)) die(Tools::displayError('Invalid objects!')); echo '<span style="width:20px; margin-right:5px;">'; if (($orderState->invoice AND $order->invoice_number) AND intval($tr['product_number'])) echo '<a href="pdf.php?id_order='.intval($order->id).'&pdf"><img src="../img/admin/tab-invoice.gif" alt="invoice" /></a>'; else echo ' '; echo '</span>'; echo '<span style="width:20px;">'; if ($orderState->delivery AND $order->delivery_number) echo '<a href="pdf.php?id_delivery='.intval($order->delivery_number).'"><img src="../img/admin/delivery.gif" alt="delivery" /></a>'; else echo ' '; echo '</span>'; } static public function getByDelivery($id_delivery) { $res = Db::getInstance()->getRow(' SELECT id_order FROM `'._DB_PREFIX_.'orders` WHERE `delivery_number` = '.intval($id_delivery)); return new Order(intval($res['id_order'])); } public function getTotalWeight() { $result = Db::getInstance()->getRow(' SELECT SUM(product_weight * product_quantity) weight FROM '._DB_PREFIX_.'order_detail WHERE id_order = '.intval($this->id));
return floatval($result['weight']); }
static public function getInvoice($id_invoice) { return Db::getInstance()->getRow(' SELECT `invoice_number`, `id_order` FROM `'._DB_PREFIX_.'orders` WHERE invoice_number = '.intval($id_invoice)); } }
?>
Добавлено через 3 часа, 43 минуты и 48 секунд:для этой формы, выбора времени, никакой ещё обработки нет, не знаюкак вообще это сделать, подскажите пожалуйста, просто вот как написать такую форму, что бы она записывала в базу данных значения, но при этом что бы она хранила много значений? т.е. что бы пользователи могли выбирать это врёмя, и у меня в админке оно для каждого заказа отображалось разное.
|
|
« Последнее редактирование: 14-06-2011 18:19 от Sega063 »
|
Записан
|
|
|
|
Sla
|
|
« Ответ #8 : 14-06-2011 20:05 » |
|
чтобы еще и в админку внедрить твои пожелания... это надолго. Движок построен по mvc-технологии. Твоя задача... понять где модель, где контроллер, а где вьювер.
Так как не хочется глубоко вникать в prestahop, тебе придется самостоятельно в этом разобраться.
А теперь смотри... Твоя форма это часть некторой "формы" (я так понял) формы order, Что это? Модель или вьювер? Я бы назвал вьювером - по сути дела шаблон. Контроллер обрабатывает полученные данные от вьювера, и передает данные в модель При заказе (order) используется как вьювер, так и контроллер, дальше я не смотрел, для обработки формы заказа. Соответсвенно тебе нужно дополнить и модель и вьювер и контроллер твоими "полями"формы.
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #9 : 14-06-2011 20:09 » |
|
Было бы не плохо всё это внедрить, вот только мозгов у меня на это не хватает, буду мучаться, может что то и получится. Спасибо за помощь! Буду теперь разбираться))) Я думал будет всё намного проще, сделаю модель, переменные, и форму для них, и просто заставить его их сохранять для каждого пользователя. а теперь понимаю что это всё очень запутанно и сложно))
|
|
|
Записан
|
|
|
|
Sla
|
|
« Ответ #10 : 14-06-2011 20:19 » |
|
Sega063, не... на самом деле это вес не сложно... в двух словах..
html форма -> запрос (вьювер) запрос -> обработчик (контроллер) обработчик -Ю модель (запись в базу
Возможно, я где-то ошибаюсь, в применении понятий... но приблизительно так.
Рекомендую рассмотреь сначала как работает форма order, как получает данные заказа сервер, как он их обрабатывает, и что он с сними делает дальше.
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #11 : 14-06-2011 20:26 » |
|
я это уже рассматривал, и вот у меня большой минус в том, что я не понимаю большинство иэтих переменных и принципа действия)) Спасибо большое за ответ! Сейчас более понятнее стало, буду искать учебники, надеюсь они мне помогут)))
|
|
|
Записан
|
|
|
|
Sla
|
|
« Ответ #12 : 14-06-2011 20:52 » |
|
здесь, увы учебники не помогут...
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #13 : 14-06-2011 20:56 » |
|
значит буду надеяться на свои знания и на удачу, авось и получится))
|
|
|
Записан
|
|
|
|
Sla
|
|
« Ответ #14 : 14-06-2011 21:02 » |
|
Sega063, на авось надейся, а сам не плошай Возникнут вопросы - милости просим. Совет... Не спеши писать свою форму... Разберись со стандартной формой заказа.
|
|
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #15 : 14-06-2011 21:04 » |
|
Спасибо большое за советы и помощь! Буду сейчас рассматривать и разбираться
|
|
|
Записан
|
|
|
|
Sla
|
|
« Ответ #16 : 14-06-2011 21:08 » |
|
Если скинешь в личку, адрес сайта, то, возможно, что-то подскажу, не хочется запускать, даже тестовый вариант pestashop
Добавлено через 10 часов, 49 минут и 35 секунд: тебе надо раскручивать контроллер OrderController.php
а в нем (step 2) Это методы $this->processAddress(); $this->autoStep(); $this->_assignCarrier();
Нужно смотреть каждый метод и узнать каким способом (через вызовы каких методов) происходит доступ к POST переменным
шаблон, в котором ты будешь создавать(менять) order-carrier.tpl
|
|
« Последнее редактирование: 15-06-2011 07:58 от Sla »
|
Записан
|
Мы все учились понемногу... Чему-нибудь и как-нибудь.
|
|
|
Sega063
Интересующийся
Offline
|
|
« Ответ #17 : 15-06-2011 08:19 » |
|
Спасибо большое за помощь!!!!!))) Теперь уже будет легче, а то я лазил, смотрел искал непонятно где)))
|
|
|
Записан
|
|
|
|
|