HOSTCMS v.6
КОРЗИНА
Выводим сообщение о том, что сумма товаров меньше чем нужно и скрываем кнопку "оформить заказ"
<xsl:if test="total_amount < 1000">
<h4>Заказ не может быть обработан, так как сумма вашего заказа менее 1000р. </h4>
</xsl:if>
<xsl:if test="total_amount > 1000">
<div class="row">
<div class="caption"></div>
<div class="field">
<input value="Оформить заказ" type="submit" class="button"/>
</div>
</div>
</xsl:if>
Корзина «В один клик»
В данном решении за основу взята стандартная ТДС1 «Интернет-магазин корзина» из релиза 6.1.2. Все заложенные возможности стандартной корзины сохранены.
1 ТДС – аббв. от Типовая динамическая страница.
2 ЦА – аббв. от Центр администрирования.
ВНИМАНИЕ! Если возникают ошибки в работе данного решения, установленного в релиз HostCMS v.6, отличающийся от вышеуказанного, необходимо написать разработчикам CMS-Modules для устранения проблем с совместимостью.
Все шаги оформления заказа объединены на одной странице. Пользователю достаточно заполнить необходимые данные и один раз нажать «Оформить заказ».
Списки платежных систем и форм оплаты обновляются посредством AJAX-технологии при каждом изменении пользователем значимых данных. Поэтому решение предназначено только для пользователей, у которых в браузере не отключен JavaScript.
Установка решения на HostCMS v.6
- Необходимо перейти в раздел «Типовые динамические страницы» ЦА2 .
- В разделе ТДС «Интернет-магазин» скопировать стандартную ТДС «Интернет-магазин корзина» (код 7), кликнув на пиктограмме .
- Отредактировать копию ТДС, кликнув на пиктограмме . Перейти на вкладку «Код страницы» и вставить php-код из файла lib.php вместо содержимого поля «PHP код типовой динамической страницы». Перейти на вкладку «Настройки страницы» и вставить php-код из файла lib_config.php вместо содержимого поля «Настройки типовой динамической страницы». Сохранить изменения, нажатием кнопки "применить".
- Необходимо перейти в раздел «Структура сайта» ЦА.
- Отредактировать узел структуры «Корзина», который по умолчанию находится внутри узла структуры «Интернет-магазин» (код 42 в релизе 6.1.2). В качестве Типовой динамической страницы, необходимо указать ТДС из п.3. Указать значения параметров ТДС, исходя из нужд Вашего проекта (можно оставить значения, которые были у узла струтуры «Корзина»). Сохранить изменения, нажатием кнопки "применить" .
- Отредактировать XSL-шаблоны «МагазинКорзина», «МагазинАдресДоставки», «МагазинДоставки» и «МагазинПлатежнаяСистема» с учетом следующих требований:
a. Обязательно в используемых XSL-шаблонах следует удалить теги <form> и </form>.
b. Следует удалить кнопки перехода на следующий шаг во всех шаблонах, кроме «МагазинПлатежнаяСистема».Для XSL-шаблоны «МагазинКорзина», это фрагмент кода:
<xsl:if test="count(shop_cart[postpone = 0]) and siteuser_id > 0 or siteuser_id = 0"> <input name="step" value="1" type="hidden" /> <input value="Оформить заказ" type="submit" class="button"/> </xsl:if>Для XSL-шаблоны «МагазинАдресДоставки», это фрагмент кода:
<div class="row"> <div class="caption"></div> <div class="field"> <input name="step" value="2" type="hidden" /> <input value="Далее →" type="submit" class="button" /> </div> </div>
Для XSL-шаблоны «МагазинДоставки», это фрагмент кода:<input name="step" value="3" type="hidden" /> <input value="Далее →" type="submit" class="button" /> -
Проверить работу
ВОЗМОЖНЫЕ ОШИБКИ:
При возникновении ошибки:
Exception: The method 'shop_delivery_id' does not exist in
'Shop_Payment_System_Controller_Show'
29 modules/core/exception.php
110 modules/core/servant/properties.php
458 hostcmsfiles/lib/lib_47/lib_47.php
268 modules/lib/model.php
100 modules/core/page.php
4 templates/template14/template.htm
83 modules/template/model.php
100 modules/core/page.php
129 templates/template13/template.htm
83 modules/template/model.php
100 modules/core/page.php
363 modules/core/command/controller/default.php
188 modules/core/router/route.php
205 index.php
Закомментировать строку в типовой, где присутствует ->shop_delivery_id(....
При отсутствии Городов в АдресеДоставки (Корзина)
В настройках типовой сделать правку. Заменить:
$aArray = array('…');
foreach ($aObjects as $Object)
{
$aArray['_' .$Object->id] = $Object->name;
}
на
$aArray = array('…');
foreach ($aObjects as $Object)
{
$aArray[$Object->id] = $Object->name;//'_' .
}
В XSL Адрес Доставки заменить
<SCRIPT type="text/javascript">
$(function() {
$.loadLocations('<xsl:value-of select="/shop/url" />cart/', $('#shop_country_id').val());
});
</SCRIPT>
на
<script>
$(function() {
$('#shop_country_id').change();
//$.loadLocations('<xsl:value-of select="/shop/url" />cart/', $('#shop_country_id option[selected]').val());
});
</script>
Если используется проверка заполнения формы, то скрипт расположить в Макете, а onSubmit = "return Formdata(this)" добавить в коде Типовой корзины в строке:
echo '<form method="post" action="./" id="cmsm-form-cart" onSubmit = "return Formdata(this)">';
LIB.PHP
для v.6.8.0 и выше
Код ТДС
<?php
$Shop_Cart_Controller_Show = Core_Page::instance()->object;
$oShop = $Shop_Cart_Controller_Show->getEntity();
Shop_Payment_System_Handler::checkAfterContent($oShop);
Shop_Delivery_Handler::checkAfterContent($oShop);
// ------------------------------------------------
// Вывод информации о статусе платежа после его совершения и перенаправления с платежной системы
// ------------------------------------------------
if (isset($_REQUEST['payment']) || (isset($_GET['action']) && ($_GET['action'] == 'PaymentSuccess' || $_GET['action'] == 'PaymentFail')) || isset($_REQUEST['pg_order_id']))
{
// Получаем ID заказа
if (isset($_REQUEST['order_id']))
{
$order_id = intval(Core_Array::getRequest('order_id'));
}
//от Яндекса
elseif(isset($_GET['orderNumber']))
{
$order_id = intval(Core_Array::getGet('orderNumber'));
}
//от PayPal
elseif(isset($_REQUEST['invoice']))
{
$oShop_Order = Core_Entity::factory('Shop_Order')->getByGuid(Core_Array::getRequest('invoice'));
$order_id = $oShop_Order ? intval($oShop_Order->id) : NULL;
}
//от IntellectMoney
elseif(isset($_REQUEST['orderId']))
{
$order_id = intval(Core_Array::getGet('orderId'));
}
//от Platron
elseif(isset($_REQUEST['pg_order_id']))
{
$order_id = intval(Core_Array::getRequest('pg_order_id'));
}
else
{
$order_id = intval(Core_Array::getRequest('InvId'));
}
$oShop_Order = Core_Entity::factory('Shop_Order')->find($order_id);
if (Core::moduleIsActive('siteuser'))
{
$siteuser_id = 0;
$oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
if ($oSiteuser)
{
$siteuser_id = $oSiteuser->id;
}
}
else
{
$siteuser_id = FALSE;
}
// Если заказ принадлежит текущему авторизированному пользователю
if ($oShop_Order->siteuser_id == $siteuser_id)
{
if (Core_Array::getRequest('payment') == 'success' || Core_Array::getRequest('action') == 'PaymentSuccess' || Core_Array::getRequest('pg_order_id') > 0)
{
?><h1>Подтверждение платежа</h1>
<p>Спасибо, информация об оплате заказа <strong>№ <?php echo $oShop_Order->invoice?></strong>
получена.</p>
<?php
}
else
{
?><h1>Платеж не получен</h1>
<p>К сожалению при оплате заказа <strong>№ <?php echo $oShop_Order->invoice?></strong> произошла ошибка.</p>
<?php
}
}
// Для случаев, когда отключен модуль "Пользователи сайта"
elseif ($siteuser_id === FALSE)
{
?><h1>Подтверждение платежа</h1>
<p>Благодарим за посещение нашего магазина!</p>
<?php
}
else
{
?><h1>Ошибка</h1>
<p>Неверный номер заказа!</p>
<?php
}
// Прерываем выполнение типовой динамической страницы
return TRUE;
}
$xslName = Core_Array::get(Core_Page::instance()->libParams, 'cartXsl');
Core_Session::start();
if (Core_Array::getPost('oneStepCheckout'))
{
// Сбрасываем информацию о последнем заказе
$_SESSION['last_order_id'] = 0;
// Оформление в один шаг
$Shop_Cart_Controller = Shop_Cart_Controller::instance();
$aShop_Cart = $Shop_Cart_Controller->getAll($oShop);
foreach ($aShop_Cart as $oShop_Cart)
{
$Shop_Cart_Controller
->shop_item_id($oShop_Cart->shop_item_id)
->delete();
}
$shop_item_id = intval(Core_Array::getRequest('shop_item_id'));
if ($shop_item_id)
{
Shop_Cart_Controller::instance()
->shop_item_id($shop_item_id)
->quantity(floatval(Core_Array::getRequest('count', 1)))
->add();
}
$_SESSION['hostcmsOrder'] = array();
$_SESSION['hostcmsOrder']['shop_country_id'] = intval(Core_Array::getPost('shop_country_id', 0));
$_SESSION['hostcmsOrder']['shop_country_location_id'] = intval(Core_Array::getPost('shop_country_location_id', 0));
$_SESSION['hostcmsOrder']['shop_country_location_city_id'] = intval(Core_Array::getPost('shop_country_location_city_id', 0));
$_SESSION['hostcmsOrder']['shop_country_location_city_area_id'] = intval(Core_Array::getPost('shop_country_location_city_area_id', 0));
$_SESSION['hostcmsOrder']['postcode'] = Core_Str::stripTags(strval(Core_Array::getPost('postcode')));
$_SESSION['hostcmsOrder']['address'] = Core_Str::stripTags(strval(Core_Array::getPost('address')));
$_SESSION['hostcmsOrder']['house'] = Core_Str::stripTags(strval(Core_Array::getPost('house')));
$_SESSION['hostcmsOrder']['flat'] = Core_Str::stripTags(strval(Core_Array::getPost('flat')));
$_SESSION['hostcmsOrder']['surname'] = Core_Str::stripTags(strval(Core_Array::getPost('surname')));
$_SESSION['hostcmsOrder']['name'] = Core_Str::stripTags(strval(Core_Array::getPost('name')));
$_SESSION['hostcmsOrder']['patronymic'] = Core_Str::stripTags(strval(Core_Array::getPost('patronymic')));
$_SESSION['hostcmsOrder']['phone'] = Core_Str::stripTags(strval(Core_Array::getPost('phone')));
$_SESSION['hostcmsOrder']['email'] = Core_Str::stripTags(strval(Core_Array::getPost('email')));
$_SESSION['hostcmsOrder']['description'] = Core_Str::stripTags(strval(Core_Array::getPost('description')));
// Additional order properties
$_SESSION['hostcmsOrder']['properties'] = array();
$oShop_Order_Property_List = Core_Entity::factory('Shop_Order_Property_List', $oShop->id);
$aProperties = $oShop_Order_Property_List->Properties->findAll();
foreach ($aProperties as $oProperty)
{
// Св-во может иметь несколько значений
$aPropertiesValue = Core_Array::getPost('property_' . $oProperty->id);
if (!is_null($aPropertiesValue))
{
!is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
foreach ($aPropertiesValue as $sPropertyValue)
{
$_SESSION['hostcmsOrder']['properties'][] = array($oProperty->id, $sPropertyValue);
}
}
}
$shop_delivery_condition_id = strval(Core_Array::getPost('shop_delivery_condition_id', 0));
if (is_numeric($shop_delivery_condition_id))
{
$_SESSION['hostcmsOrder']['shop_delivery_condition_id'] = intval($shop_delivery_condition_id);
$oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', $_SESSION['hostcmsOrder']['shop_delivery_condition_id']);
$_SESSION['hostcmsOrder']['shop_delivery_id'] = $oShop_Delivery_Condition->shop_delivery_id;
}
$_POST['step'] = 4;
}
// Проверяем наличие товара в корзины
$Shop_Cart_Controller = Shop_Cart_Controller::instance();
$aShop_Cart = $Shop_Cart_Controller->getAll($oShop);
switch (Core_Array::getPost('recount') || !count($aShop_Cart) ? 0 : Core_Array::getPost('step'))
{
// Окончание оформления заказа
case 4:
// Сбрасываем информацию о последнем заказе
$_SESSION['last_order_id'] = 0;
// Заполнение данных доставки
$_SESSION['hostcmsOrder']['shop_country_id'] = intval(Core_Array::getPost('shop_country_id', 0));
$_SESSION['hostcmsOrder']['shop_country_location_id'] = intval(Core_Array::getPost('shop_country_location_id', 0));
$_SESSION['hostcmsOrder']['shop_country_location_city_id'] = intval(Core_Array::getPost('shop_country_location_city_id', 0));
$_SESSION['hostcmsOrder']['shop_country_location_city_area_id'] = intval(Core_Array::getPost('shop_country_location_city_area_id', 0));
$_SESSION['hostcmsOrder']['postcode'] = strval(Core_Array::getPost('postcode'));
$_SESSION['hostcmsOrder']['address'] = strval(Core_Array::getPost('address'));
$_SESSION['hostcmsOrder']['surname'] = strval(Core_Array::getPost('surname'));
$_SESSION['hostcmsOrder']['name'] = strval(Core_Array::getPost('name'));
$_SESSION['hostcmsOrder']['patronymic'] = strval(Core_Array::getPost('patronymic'));
$_SESSION['hostcmsOrder']['company'] = strval(Core_Array::getPost('company'));
$_SESSION['hostcmsOrder']['phone'] = strval(Core_Array::getPost('phone'));
$_SESSION['hostcmsOrder']['fax'] = strval(Core_Array::getPost('fax'));
$_SESSION['hostcmsOrder']['email'] = strval(Core_Array::getPost('email'));
$_SESSION['hostcmsOrder']['description'] = strval(Core_Array::getPost('description'));
$_SESSION['hostcmsOrder']['tin'] = strval(Core_Array::getPost('tin'));
$_SESSION['hostcmsOrder']['kpp'] = strval(Core_Array::getPost('kpp'));
// Additional order properties
$_SESSION['hostcmsOrder']['properties'] = array();
$oShop_Order_Property_List = Core_Entity::factory('Shop_Order_Property_List', $oShop->id);
$aProperties = $oShop_Order_Property_List->Properties->findAll();
foreach ($aProperties as $oProperty){
// Св-во может иметь несколько значений
$aPropertiesValue = Core_Array::getPost('property_' . $oProperty->id);
if (!is_null($aPropertiesValue))
{
!is_array($aPropertiesValue) && $aPropertiesValue = array($aPropertiesValue);
foreach ($aPropertiesValue as $sPropertyValue)
{
$_SESSION['hostcmsOrder']['properties'][] = array($oProperty->id, $sPropertyValue);
}
}
}
//~~ Заполнение данных доставки
// Выбор условия доставки
$shop_delivery_condition_id = strval(Core_Array::getPost('shop_delivery_condition_id', 0));
if (is_numeric($shop_delivery_condition_id))
{
$_SESSION['hostcmsOrder']['shop_delivery_condition_id'] = intval($shop_delivery_condition_id);
}
else
{
$_SESSION['hostcmsOrder']['shop_delivery_condition_id'] = 0;
// в shop_delivery_condition_id тогда "123#", ID элемента массива в сессии, в котором
// хранится стоимость доставки, налог, название специфичного условия доставки
list($shopDeliveryInSession) = explode('#', $shop_delivery_condition_id);
if (isset($_SESSION['hostcmsOrder']['deliveries'][$shopDeliveryInSession]))
{
$aTmp = $_SESSION['hostcmsOrder']['deliveries'][$shopDeliveryInSession];
$_SESSION['hostcmsOrder']['shop_delivery_id'] = $aTmp['shop_delivery_id'];
$_SESSION['hostcmsOrder']['shop_delivery_price'] = $aTmp['price'];
$_SESSION['hostcmsOrder']['shop_delivery_rate'] = $aTmp['rate'];
$_SESSION['hostcmsOrder']['shop_delivery_name'] = $aTmp['name'];
}
}
//~~ Выбор условия доставки
// Выбор формы оплаты
$shop_payment_system_id = $_SESSION['hostcmsOrder']['shop_payment_system_id'] = intval(Core_Array::getPost('shop_payment_system_id', 0));
// Если выбрана платежная система
if ($_SESSION['hostcmsOrder']['shop_payment_system_id'])
{
Shop_Payment_System_Handler::factory(
Core_Entity::factory('Shop_Payment_System', $shop_payment_system_id)
)
->orderParams($_SESSION['hostcmsOrder'])
->execute();
}
else
{
?><h1>Ошибка! Не указана ни одна платежная система.</h1><?php
}
//~~ Выбор формы оплаты
break;
// Адрес доставки
case 1:
// Способ доставки
case 2:
// Форма оплаты
case 3:
default:
echo '<form method="post" action="./" id="cmsm-form-cart">';
echo '<scr'.strtolower('I').'pt>';
echo '$(function(){
$("#cmsm-form-cart").on("change", "select[name=shop_country_id], select[name=shop_country_location_id], select[name=shop_country_location_city_id], select[name=shop_country_location_city_area_id], input[name=postcode], input[name=coupon_text]", function(){
$.loadingScreen("show"); // Крутилка
$.ajax({
url: "./",
type: "GET",
data: ({"CMSMajaxLoadDelivery" : 1, "shop_country_id" : $("select[name=shop_country_id] :selected").val(), "shop_country_location_id" : $("select[name=shop_country_location_id] :selected").val(), "shop_country_location_city_id" : $("select[name=shop_country_location_city_id] :selected").val(), "shop_country_location_city_area_id" : $("select[name=shop_country_location_city_area_id] :selected").val(), "postcode" : $("input[name=postcode]").val(), "coupon_text" : $("input[name=coupon_text]").val()}),
dataType: "html",
success: function(html){
$("#shop-delivery-block").empty().append(html);
$.loadingScreen("hide"); // Убираем крутилку
$("input[name=shop_delivery_condition_id]").change();
}
});
return true;
});
$("#cmsm-form-cart").on("change", "input[name=shop_delivery_condition_id]", function(){
$.loadingScreen("show"); // Крутилка
$.ajax({
url: "./",
type: "GET",
data: ({"CMSMajaxLoadPayment" : 1, "shop_delivery_condition_id" : $("input[name=shop_delivery_condition_id]:checked").val()}),
dataType: "html",
success: function(html){
$("#shop-payment-block").empty().append(html);
$.loadingScreen("hide"); // Убираем крутилку
}
});
return true;
});
if ($("select[name=shop_country_id]").change())
$("input[name=shop_delivery_condition_id]").change();
});
';
echo '</sc'.'ri'.strtolower('PT').'>';
// Корзина
$Shop_Cart_Controller_Show
->couponText(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'coupon_text'))
->xsl(
Core_Entity::factory('Xsl')->getByName($xslName)
)
->itemsProperties(TRUE)
->show();
// Корзина не пуста
if (count($aShop_Cart)){
echo ' <h3>Оформление заказа <br /><span class="small">(выберите свой город, чтобы увидеть все доставки)</span></h3><div class="order">';
echo '<div id="shop-address-block" class="col-xs-12 col-md-4 box2 match-height">';
// Адрес доставки
$Shop_Address_Controller_Show = new Shop_Address_Controller_Show($oShop);
$Shop_Address_Controller_Show->xsl(
Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'deliveryAddressXsl')
)
)
->show();
echo '</div>';
echo '<div id="shop-delivery-block" class="col-xs-12 col-md-4 box2 match-height">';
// Способ доставки
$Shop_Delivery_Controller_Show = new Shop_Delivery_Controller_Show($oShop);
$Shop_Delivery_Controller_Show
->shop_country_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_id'))
->shop_country_location_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_location_id'))
->shop_country_location_city_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_location_city_id'))
->shop_country_location_city_area_id(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_country_location_city_area_id'))
->couponText(Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'coupon_text'))
->setUp()
->xsl(
Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'deliveryXsl')
)
)
->show();
echo '</div>';
echo '<div id="shop-payment-block" class="col-xs-12 col-md-4 box2 match-height">';
// Форма оплаты
$oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'shop_delivery_condition_id'));
$Shop_Payment_System_Controller_Show = new Shop_Payment_System_Controller_Show($oShop);
$Shop_Payment_System_Controller_Show
->shop_delivery_id($oShop_Delivery_Condition->shop_delivery_id)
->xsl(
Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'paymentSystemXsl')
)
)
->show();
echo '</div>';
}
echo '</div></form>';
}
// Блок авторизации пользователя
if (Core::moduleIsActive('siteuser'))
{
$oSiteuser = Core_Entity::factory('Siteuser')->getCurrent();
if (is_null($oSiteuser))
{
// Авторизация
$Siteuser_Controller_Show = new Siteuser_Controller_Show(
Core_Entity::factory('Siteuser')
);
$Siteuser_Controller_Show
->location(Core::$url['path'])
->xsl(
Core_Entity::factory('Xsl')->getByName(Core_Array::get(Core_Page::instance()->libParams, 'userAuthorizationXsl'))
)
->show();
// Регистрация
$Siteuser_Controller_Show = new Siteuser_Controller_Show(
Core_Entity::factory('Siteuser')
);
$Siteuser_Controller_Show->xsl(
Core_Entity::factory('Xsl')->getByName(Core_Array::get(Core_Page::instance()->libParams, 'userRegistrationXsl'))
)
->location(Core::$url['path'])
->fastRegistration(TRUE)
->itemsProperties(TRUE)
->properties(TRUE)
//->showMaillists(TRUE)
->show();
}
}
Код настроек ТДС
<?php
$oShop = Core_Entity::factory('Shop', Core_Array::get(Core_Page::instance()->libParams, 'shopId'));
// Проверять остаток на складе при добавлении в корзину
$bCheckStock = FALSE;
Shop_Payment_System_Handler::checkBeforeContent($oShop);
Shop_Delivery_Handler::checkBeforeContent($oShop);
// Добавление товара в корзину
if (Core_Array::getRequest('add'))
{
$shop_item_id = intval(Core_Array::getRequest('add'));
if ($shop_item_id)
{
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$oShop_Cart_Controller
->shop_item_id($shop_item_id)
->quantity(Core_Array::getRequest('count', 1))
->add();
}
// Ajax
if (Core_Array::getRequest('_', FALSE))
{
ob_start();
// Краткая корзина
$Shop_Cart_Controller_Show = new Shop_Cart_Controller_Show(
$oShop
);
$Shop_Cart_Controller_Show
->xsl(
Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'littleCartXsl')
)
)
->couponText(Core_Array::get($_SESSION, 'coupon_text'))
->show();
echo json_encode(ob_get_clean());
exit();
}
}
// Быстрый заказ в 1 клик
if (!is_null(Core_Array::getRequest('oneStepCheckout')))
{
$shop_item_id = intval(Core_Array::getRequest('shop_item_id'));
$Shop_Cart_Controller_Onestep = new Shop_Cart_Controller_Onestep($oShop);
// Генерация окна с заказом в 1 клик
if (!is_null(Core_Array::getRequest('showDialog'))
&& Core_Array::getRequest('_', FALSE)
&& $shop_item_id
)
{
ob_start();
$oneStepXslName = Core_Array::get(Core_Page::instance()->libParams, 'oneStepXsl');
$iQuantity = Core_Array::getRequest('count', 1);
$Shop_Cart_Controller_Onestep
->xsl(
Core_Entity::factory('Xsl')->getByName($oneStepXslName)
)
->shop_item_id($shop_item_id)
->quantity($iQuantity);
$Shop_Cart_Controller_Onestep->addEntity(
Core::factory('Core_Xml_Entity')
->name('count')->value($iQuantity)
);
$Shop_Cart_Controller_Onestep->show();
echo json_encode(array('html' => ob_get_clean(), 'id' => $shop_item_id));
exit();
}
// Список доставок
if (!is_null(Core_Array::getRequest('showDelivery')))
{
$shop_country_id = Core_Array::getRequest('shop_country_id', 0);
$shop_country_location_id = Core_Array::getRequest('shop_country_location_id', 0);
$shop_country_location_city_id = Core_Array::getRequest('shop_country_location_city_id', 0);
$shop_country_location_city_area_id = Core_Array::getRequest('shop_country_location_city_area_id', 0);
$oShop_Item = Core_Entity::factory('Shop_Item')->find($shop_item_id);
if (!is_null($oShop_Item->id))
{
$aTotal = $Shop_Cart_Controller_Onestep->quantity(Core_Array::getRequest('count', 1))->calculatePrice($oShop_Item);
$aDelivery = $Shop_Cart_Controller_Onestep->showDelivery($shop_country_id, $shop_country_location_id, $shop_country_location_city_id, $shop_country_location_city_area_id, $aTotal['weight'], $aTotal['amount']);
echo json_encode(array('delivery' => $aDelivery));
exit();
}
}
// Список платежных систем
if (!is_null(Core_Array::getRequest('showPaymentSystem')))
{
$shop_delivery_condition_id = strval(Core_Array::getGet('shop_delivery_condition_id', 0));
$aPaymentSystems = array();
if (is_numeric($shop_delivery_condition_id))
{
$oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', $shop_delivery_condition_id);
$aPaymentSystems = $Shop_Cart_Controller_Onestep->showPaymentSystem($oShop_Delivery_Condition->shop_delivery_id);
}
echo json_encode(array('payment_systems' => $aPaymentSystems));
exit();
}
}
if (Core_Array::getGet('action') == 'repeat')
{
$guid = Core_Array::getGet('guid');
if (strlen($guid))
{
$oShop_Order = $oShop->Shop_Orders->getByGuid($guid);
if (!is_null($oShop_Order))
{
$aShop_Order_Items = $oShop_Order->Shop_Order_Items->findAll();
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
foreach ($aShop_Order_Items as $oShop_Order_Item)
{
$oShop_Order_Item->shop_item_id && $oShop_Cart_Controller
->shop_item_id($oShop_Order_Item->shop_item_id)
->quantity($oShop_Order_Item->quantity)
->add();
}
}
}
}
if (!is_null(Core_Array::getGet('ajaxLoad')))
{
if (!is_null(Core_Array::getGet('city_name')))
{
$shop_country_id = intval(Core_Array::getGet('shop_country_id'));
$aArray = array('…');
$oCurrent_Shop_Country_Location_Cities = Core_Entity::factory('Shop_Country_Location_City');
$oCurrent_Shop_Country_Location_Cities->queryBuilder()
->join('shop_country_locations', 'shop_country_locations.id', '=', 'shop_country_location_cities.shop_country_location_id')
->where('shop_country_locations.shop_country_id', '=', $shop_country_id);
$oCurrent_Shop_Country_Location_City = $oCurrent_Shop_Country_Location_Cities->getByName(strval(Core_Array::getGet('city_name')));
if (!is_null($oCurrent_Shop_Country_Location_City))
{
$aCities = $oCurrent_Shop_Country_Location_City
->Shop_Country_Location
->Shop_Country_Location_Cities
->findAll(FALSE);
foreach ($aCities as $Object)
{
$aArray['cities']['_' . $Object->id] = $Object->getName();
}
$aArray['result'] = array(
'shop_country_location_id' => $oCurrent_Shop_Country_Location_City->shop_country_location_id,
'shop_country_location_city_id' => $oCurrent_Shop_Country_Location_City->id
);
}
Core::showJson($aArray);
}
$aObjects = array();
if (Core_Array::getGet('shop_country_id'))
{
$oShop_Country_Location = Core_Entity::factory('Shop_Country_Location');
$oShop_Country_Location
->queryBuilder()
->where('shop_country_id', '=', intval(Core_Array::getGet('shop_country_id')));
$aObjects = $oShop_Country_Location->findAll();
}
elseif (Core_Array::getGet('shop_country_location_id'))
{
$oShop_Country_Location_City = Core_Entity::factory('Shop_Country_Location_City');
$oShop_Country_Location_City
->queryBuilder()
->where('shop_country_location_id', '=', intval(Core_Array::getGet('shop_country_location_id')));
$aObjects = $oShop_Country_Location_City->findAll();
}
elseif (Core_Array::getGet('shop_country_location_city_id'))
{
$oShop_Country_Location_City_Area = Core_Entity::factory('Shop_Country_Location_City_Area');
$oShop_Country_Location_City_Area
->queryBuilder()
->where('shop_country_location_city_id', '=', intval(Core_Array::getGet('shop_country_location_city_id')));
$aObjects = $oShop_Country_Location_City_Area->findAll();
}
$aArray = array('…');
foreach ($aObjects as $Object)
{
//$aArray['_' . $Object->id] = $Object->name;
$aArray['_' . $Object->id] = $Object->getName();
}
Core::showJson($aArray);
}
if (!is_null(Core_Array::getGet('CMSMajaxLoadDelivery'))){
// Способ доставки
$Shop_Delivery_Controller_Show = new Shop_Delivery_Controller_Show($oShop);
$Shop_Delivery_Controller_Show
->shop_country_id(intval(Core_Array::getGet('shop_country_id', 0)))
->shop_country_location_id(intval(Core_Array::getGet('shop_country_location_id', 0)))
->shop_country_location_city_id(intval(Core_Array::getGet('shop_country_location_city_id', 0)))
->shop_country_location_city_area_id(intval(Core_Array::getGet('shop_country_location_city_area_id', 0)))
->couponText(trim(strval(Core_Array::getGet('coupon_text', Core_Array::get(Core_Array::get($_SESSION, 'hostcmsOrder', array()), 'coupon_text')))))
->postcode(strval(Core_Array::getGet('postcode')))
->setUp()
->xsl(
Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'deliveryXsl')
)
)
->show();
exit();
}
if (!is_null(Core_Array::getGet('CMSMajaxLoadPayment'))){
// Форма оплаты
$oShop_Delivery_Condition = Core_Entity::factory('Shop_Delivery_Condition', intval(Core_Array::getGet('shop_delivery_condition_id', 0)));
$Shop_Payment_System_Controller_Show = new Shop_Payment_System_Controller_Show($oShop);
$Shop_Payment_System_Controller_Show
->shop_delivery_id($oShop_Delivery_Condition->shop_delivery_id)
->xsl(
Core_Entity::factory('Xsl')->getByName(
Core_Array::get(Core_Page::instance()->libParams, 'paymentSystemXsl')
)
)
->show();
exit();
}
// Удаление товара из корзины
if (Core_Array::getGet('delete'))
{
$shop_item_id = intval(Core_Array::getGet('delete'));
if ($shop_item_id)
{
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$oShop_Cart_Controller
->shop_item_id($shop_item_id)
->delete();
}
}
// Запоминаем купон
if (!is_null(Core_Array::getRequest('coupon_text')))
{
Core_Session::start();
$_SESSION['hostcmsOrder']['coupon_text'] = trim(strval(Core_Array::getRequest('coupon_text')));
}
if (Core_Array::getPost('recount') || Core_Array::getPost('step') == 1)
{
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$aCart = $oShop_Cart_Controller->getAll($oShop);
// Склад по умолчанию
$oShop_Warehouse = $oShop->Shop_Warehouses->getDefault();
foreach ($aCart as $oShop_Cart)
{
$quantity = Core_Array::getPost('quantity_' . $oShop_Cart->shop_item_id);
// Количество было передано
if (!is_null($quantity))
{
$oShop_Cart_Controller
->clear()
->checkStock($bCheckStock)
->shop_item_id($oShop_Cart->shop_item_id)
->quantity($quantity)
->postpone(is_null(Core_Array::getPost('postpone_' . $oShop_Cart->shop_item_id)) ? 0 : 1)
->shop_warehouse_id(
Core_Array::getPost('warehouse_' . $oShop_Cart->shop_item_id, !is_null($oShop_Warehouse) ? $oShop_Warehouse->id : 0)
)
->update();
}
}
}
$Shop_Cart_Controller_Show = new Shop_Cart_Controller_Show($oShop);
Core_Page::instance()->object = $Shop_Cart_Controller_Show;

КОРЗИНА-КРАТКАЯ в модальном окне
<head> код для Краткой корзины.<a class="button" onclick="return $.bootstrapAddIntoCart('{/shop/url}cart/', {@id}, 1)" href="#" data-toggle="modal" data-target="#basicModal">
<span class="bg-color3"><i class="fa fa-shopping-cart bg-color5"></i>
<span>В корзину</span>
</span>
</a>
<div class="modal fade" id="basicModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-box">
<div class="modal-header"><button class="close" type="button" data-dismiss="modal">x</button>
<h2 class="modal-title" id="myModalLabel">Ваша корзина покупок</h2>
</div>
<div class="little-cart">
<?php
if (Core::moduleIsActive('shop'))
{
// Краткая корзина
$Shop_Cart_Controller_Show = new Shop_Cart_Controller_Show(
Core_Entity::factory('Shop', 3)
);
$Shop_Cart_Controller_Show
->xsl(
Core_Entity::factory('Xsl')->getByName('МагазинКорзинаКраткаяСайт2')
)
->couponText(isset($_SESSION) ? Core_Array::get($_SESSION, 'coupon_text') : '')
->itemsPropertiesList(FALSE)
->show();
}
?>
</div>
</div>
</div>
</div>
</div>
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xsl:stylesheet>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:hostcms="http://www.hostcms.ru/"
exclude-result-prefixes="hostcms">
<xsl:output xmlns="http://www.w3.org/TR/xhtml1/strict" doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" encoding="utf-8" indent="yes" method="html" omit-xml-declaration="no" version="1.0" media-type="text/xml"/>
<!-- МагазинКорзинаКраткая -->
<xsl:decimal-format name="my" decimal-separator="," grouping-separator=" "/>
<xsl:template match="/shop">
<div class="modal-cart mt-cart">
<div class="little-cart-info">
<xsl:choose>
<!-- В корзине нет ни одного элемента -->
<xsl:when test="count(shop_cart) = 0">
<div class="empty-cart">
<div>0 товаров — 0 руб.</div>
</div>
</xsl:when>
<xsl:otherwise>
<div class="full-cart">
<div>
<xsl:variable name="totalQuantity" select="sum(shop_cart[postpone = 0]/quantity)" />
<!-- Вывод общих количества, веса и стоимости товаров -->
<xsl:value-of select="$totalQuantity"/>
<xsl:text> </xsl:text><xsl:call-template name="declension"><xsl:with-param name="number" select="$totalQuantity"/></xsl:call-template>
<xsl:text> на сумму </xsl:text><xsl:value-of select="format-number(total_amount, '### ##0,00', 'my')"/><xsl:text> </xsl:text><xsl:value-of disable-output-escaping="yes" select="shop_currency/name"/>
</div>
</div>
</xsl:otherwise>
</xsl:choose>
</div>
<div class="more-cart">
<xsl:choose>
<!-- В корзине нет ни одного элемента -->
<xsl:when test="count(shop_cart[postpone = 0]) = 0">
<div class="cart-item-list-empty">В корзине нет ни одного товара</div>
</xsl:when>
<xsl:otherwise>
<div class="row cart-item-list">
<xsl:apply-templates select="shop_cart[postpone = 0]/shop_item" />
</div>
<div class="cart-link"><a href="/shop/cart/" class="button"><span class="bg-color2"><span>ОФОРМИТЬ ЗАКАЗ</span></span></a></div>
</xsl:otherwise>
</xsl:choose>
</div>
</div>
</xsl:template>
<xsl:template match="shop_item">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 cart-item clearfix">
<a class="cart-item-image" title="{name}" href="{url}">
<xsl:choose>
<xsl:when test="image_small != ''">
<img alt="{name}" src="{dir}{image_small}" />
</xsl:when>
<!-- Картинка родительского товара -->
<xsl:when test="modification_id and shop_item/image_small != ''">
<img alt="{name}" src="{shop_item/dir}{shop_item/image_small}" />
</xsl:when>
<xsl:otherwise></xsl:otherwise>
</xsl:choose>
</a>
<div class="cart-item-details">
<div class="cart-item-name">
<a href="{url}"><xsl:value-of disable-output-escaping="yes" select="name"/></a>
</div>
<div class="cart-price">
<xsl:value-of disable-output-escaping="yes" select="price"/><xsl:text> </xsl:text><xsl:value-of disable-output-escaping="yes" select="/shop/shop_currency/name"/>
</div>
</div>
</div>
</xsl:template>
<!-- Склонение после числительных -->
<xsl:template name="declension">
<xsl:param name="number" select="number"/>
<!-- Именительный падеж -->
<xsl:variable name="nominative">
<xsl:text>товар</xsl:text>
</xsl:variable>
<!-- Родительный падеж, единственное число -->
<xsl:variable name="genitive_singular">
<xsl:text>товара</xsl:text>
</xsl:variable>
<xsl:variable name="genitive_plural">
<xsl:text>товаров</xsl:text>
</xsl:variable>
<xsl:variable name="last_digit">
<xsl:value-of select="$number mod 10"/>
</xsl:variable>
<xsl:variable name="last_two_digits">
<xsl:value-of select="$number mod 100"/>
</xsl:variable>
<xsl:choose>
<xsl:when test="$last_digit = 1 and $last_two_digits != 11">
<xsl:value-of select="$nominative"/>
</xsl:when>
<xsl:when test="$last_digit = 2 and $last_two_digits != 12 or $last_digit = 3 and $last_two_digits != 13 or $last_digit = 4 and $last_two_digits != 14">
<xsl:value-of select="$genitive_singular"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$genitive_plural"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>

Стили CSS . Стили для модального окна и корзины
КОРЗИНА. Добавляем минимальное количество из Допсвойства
min_quantity, тип - строка, в котором будем указывать минимальное количество товара для заказа.<!-- Проверяем задано ли минимальное количество для заказа -->
<xsl:choose>
<xsl:when test="property_value[tag_name='min_quantity']/value !='' ">
<xsl:variable name="string" select="property_value[tag_name='min_quantity']/value"/>
<!-- Здесь удаляем из записи буквы -->
<xsl:variable name="quantum1" select="translate($string, translate($string,'0123456789,',''),'')" />
<!-- Здесь удаляем из цифр пробелы и точку -->
<xsl:variable name="quantum" select="translate($quantum1, ',' , '.')" />
<a href="#" class="shop-item-add-to-cart-link pull-right" onclick="return $.bootstrapAddIntoCart('{/shop/url}cart/', {@id}, {$quantum}); " title="В корзину" data-toggle="modal" data-target="#basicModal77">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x color3"></i>
<i class="fa fa fa-shopping-cart fa-stack-1x fa-inverse"></i>
</span>
</a>
</xsl:when>
<xsl:otherwise>
<a href="#" class="shop-item-add-to-cart-link pull-right" onclick="return $.bootstrapAddIntoCart('{/shop/url}cart/', {@id}, 1); " title="В корзину" data-toggle="modal" data-target="#basicModal77">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x color3"></i>
<i class="fa fa fa-shopping-cart fa-stack-1x fa-inverse"></i>
</span>
</a>
</xsl:otherwise>
</xsl:choose>
КОРЗИНА. ОФОРМЛЕНИЕ ЗАКАЗА
<script type="text/javascript">
jQuery(function($) {
// Функция создания label
$('.row:has("*[required]") .caption').append( $('<span></span>', {class: 'label-required', text: 'Обязательное поле'}) );
// Функция включения/отключения submit
$('#shop_country_location_city_id').on('change', function() {
if($(this).val().indexOf('...') != 1) $('input:submit', this.form).attr('disabled', false);
else $('input:submit', this.form).attr('disabled', true);
}).customAutocomplete({
STRinput: '<input class="autocomplete-input" required="required" type="text" />'
}).hide();
$(document).ajaxSuccess(function() { $('#shop_country_location_city_id').customAutocomplete(); });
$.loadLocations('/shop/cart/', 256);
$.loadCities('/shop/cart/', 932);
$('#_cart input[name*="quantity_"]').on('input',function(){
if( $(this).val() != '' && $(this).val() > 0)
{
setTimeout($.proxy(function() {
$.recount_cart('/shop/cart/', $(this).attr('id'), $(this).val())
}, this), 500);
}
});
});
(function($){
// Функции без создания коллекции
$.extend({
loadCityAreas: function(path, shop_country_location_city_id)
{
if(shop_country_location_city_id=='') shop_country_location_city_id = 0;
$.clientRequest({path: path + '?load_delivery=' + shop_country_location_city_id , 'callBack': $.addIntoCartCallback, context: $('#Shop_Deliveries')});
},
recount_cart: function(path, shop_item, count)
{
$.clientRequest({path: path + '?ajax_recount=' + shop_item + '&count=' + count, 'callBack': $.addIntoCartCallback, context: $('#_cart')});
},
ajax_delete: function(path, shop_item)
{
$.clientRequest({path: path + '?ajax_delete=' + shop_item, 'callBack': $.addIntoCartCallback, context: $('#_cart')});
return false;
},
});
})(jQuery);
</script>
<div class="comment shop_address">
<input type="hidden" name="shop_country_id" value="256">
<input type="hidden" name="shop_country_location_id" value="932">
<div class="row">
<div class="caption">Имя:<span class="label-required">Обязательное поле</span></div>
<div class="field">
<input required="required" type="text" size="15" class="width1" name="name" value="">
</div>
</div>
<div class="row">
<div class="caption">Телефон:<span class="label-required">Обязательное поле</span></div>
<div class="field">
<input required="required" type="text" size="30" name="phone" value="" class="width2">
</div>
</div>
<div class="row address" style="display: none;">
<div class="caption">Адрес:<span class="label-required">Обязательное поле</span></div>
<div class="field">
<input type="text" size="30" name="address" value="" class="width2">
</div>
</div>
<div class="row">
<div class="caption">Эл. почта:</div>
<div class="field">
<input type="text" size="30" name="email" value="" class="width2">
</div>
</div>
</div>

Удаление всех товаров из корзины
Для того, чтобы дать возможность пользователю удалить из корзины сразу все товары необходимо:
1. Добавить в настройки ТДС корзины перед строкой
Core_Page::instance()->object = $Shop_Cart_Controller_Show
вот этот код:
// Удаление всех товаров из корзины
if (Core_Array::getGet('delete_all'))
{
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$oItemsInCart = $oShop_Cart_Controller->getAll($oShop);
foreach( $oItemsInCart as $oItemInCart)
{
$oShop_Cart_Controller
->shop_item_id($oItemInCart->shop_item_id)
->delete();
}
}
2. Для удаления всех товаров в XSL шаблоне Корзины разместить ссылку
<a title="Удалить все товары из заказа" onclick="return confirm('Вы уверены, что хотите удалить все товары из заказа?')" href="/shop/cart/?delete_all=1">Удалить все</a>УДАЛЕНИЕ И ДОБАВЛЕНИЕ ТОВАРОВ В КРАТКОЙ КОРЗИНЕ
// Добавление товара в корзину
if (Core_Array::getRequest('add')) ...
// Ajax Обновление товара в корзине
if (Core_Array::getRequest('updateCart')) {
$shop_item_id = intval(Core_Array::getRequest('updateCart'));
$count = intval(Core_Array::getRequest('count'));
if (($shop_item_id) && ($count)) {
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$oShop_Cart_Controller
->checkStock($bCheckStock)
->shop_item_id($shop_item_id)
->quantity($count)
->update();
}
}
// Ajax Удаляение товара из корзины
if (Core_Array::getRequest('deleteCart')) {
$shop_item_id = intval(Core_Array::getRequest('deleteCart'));
if ($shop_item_id) {
$oShop_Cart_Controller = Shop_Cart_Controller::instance();
$oShop_Cart_Controller
->shop_item_id($shop_item_id)
->delete();
}
}
// Ajax
if (Core_Array::getRequest('_', FALSE) && (Core_Array::getRequest('add') || Core_Array::getRequest('loadCart')))
// Ajax
if (Core_Array::getRequest('_', FALSE) && (Core_Array::getRequest('add') || Core_Array::getRequest('loadCart') || Core_Array::getRequest('updateCart') || Core_Array::getRequest('deleteCart')))
// Функции без создания коллекции
$.extend({
...
updateCart: function(path, shop_item_id, count){
$.clientRequest({
path: path + '?updateCart=' + shop_item_id + '&count=' + count,
callBack: $.updelCallback,
context: $('.little-cart')
});
return false;
},
deleteCart: function(path, shop_item_id){
$.clientRequest({
path: path + '?deleteCart=' + shop_item_id,
callBack: $.updelCallback,
context: $('.little-cart')
});
return false;
},
updelCallback: function(data, status, jqXHR){
$.loadingScreen('hide');
$(this).html(data);
}
<xsl:variable name="kol" select="../quantity" />
<xsl:variable name="cena" select="format-number(price, '#####0,##', 'my')" />
Стоимость: <xsl:value-of select="$cena * $kol"/>
<br />
Кол-во: <xsl:value-of select="$kol"/>
<br />
<a href="#" onclick="return $.updateCart('{/shop/url}cart/', {@id}, {$kol}+1)">Добавить</a>
<br />
<a href="#" onclick="return $.updateCart('{/shop/url}cart/', {@id}, {$kol}-1)">Убавить</a>
<br />
<a href="#" onclick="return $.deleteCart('{/shop/url}cart/', {@id})">Удалить</a>
<p>Сумма: <xsl:value-of select="total_amount"/><xsl:text> </xsl:text><xsl:value-of select="shop_currency/name"/></p>
Добавить, Убавить и Удалить лучше всего доработать и заменить на иконки