Jump to content

Выдает переменные одного товара для всех в хуке при включенном кэше


Recommended Posts

Всем здравствуйте.

 

ПРЕДЫСТОРИЯ 

 

Сделал модуль, показывающий в хуке displayProductListReviews (то есть в списке товаров у каждого товара) количество и наличие его в корзине, с кнопками + - на js. Разрабатывал, естественно с отключенным кэшем, все работает, на всех страницах где есть хук, по-тестировал слегка, все ок. Но как только включил кэш, то сразу пошли глюки на главной странице в модулях "новые", "популярные", и "скидки", на остальных - все работает как часы, но на главной полный капут.

 

ЧТО ВЫЯСНИЛ

 

1) что на главной почему то не выводятся переменные для javascript, в отличие от остальных страниц, при этом сам магазин не страдает, а модулю есть нечего, костылем то закрою, но это еще не все.

 

2) при включенном кэше в модулях "новые" "популярные" "хиты" через хук displayProductListReviews в шаблоне product-lis.tpl в переменную $product для каждого товара приходят данные одного и того же (первого в выборке) товара, то есть один и тот же айдишник и т.п. Как так может быть ума не приложу, ведь сами товары разные, а через хук вылезает один и тот же для всех. При отключении кэша - все ок, для каждого товара как положено приходят свои данные.

 

Не могу понять это баг престы? или я не учел работу хуков с кэшем?

 

Если я не учел кэш, как как это сделать. Функцию хука в модуле прикладываю.

Баг проявляется на дефолтной версии престы (на других так же), поэтому все файлы кроме модуля имеют дефолтный код.

 

Дальше пока просто не полез решил сюда написать. Помогите, люди добрые, кто чем знает.

 

public function hookDisplayProductListReviews($params)
{


        $cart = $this->context->cart;
        $in_cart_count_total = Cart::getNbProducts((int)$this->context->cart->id);
$id_product = (int)$params['product']['id_product'];
        $product_in_cart_count = $this->productInCartCount($id_product);


$this->smarty->assign(array(
'product' => $params['product'],
            'product_in_cart' => $this->getProductFromCart($id_product),
            'in_cart_count' => $product_in_cart_count,
            'id_customization' => (int)Tools::getValue('id_customization'),
            'priceDisplay' => 1,
            'currency' => $this->context->currency
));
        return $this->display(__FILE__, 'incartquantity.tpl');
}

Листинг incartquantity.tpl следующий

<!-- InCartQuantity module -->
<div class="in_cart_qty">
    
    <div class="in_cart_qty_label{if $in_cart_count > 0} marked{/if}">
        {l s='in cart' mod='incartquantity'}<span class="remove"{if $in_cart_count < 1} style="display:none;"{/if}><i class="icon-times-circle"></i></span>
    </div>
    <div class="cart_quantity_button clearfix">
    		<a
    			id="cart_quantity_down_{$product.id_product}_{$product.id_product_attribute}_{$id_customization}_{$product.id_address_delivery|intval}"
    			class="cart_quantity_down btn btn-default button-minus"
    			{*href="{$link->getPageLink('cart', true, NULL, "add=1&id_product={$product.id_product|intval}&ipa={$product.id_product_attribute|intval}&id_address_delivery={$product.id_address_delivery}&id_customization={$id_customization}&op=down&token={$token_cart}")|escape:'html':'UTF-8'}"*}
    			rel="nofollow"
    			title="{l s='Subtract'}">
    			<span><i class="icon-minus"></i></span>
    		</a>
            <input type="hidden" value="{$in_cart_count}" name="quantity_{$product.id_product}_{$product.id_product_attribute}_{$id_customization}_{$product.id_address_delivery|intval}_hidden"/>
            <input type="text" value="{$in_cart_count}" class="cart_quantity_input form-control grey" name="quantity_{$product.id_product}_{$product.id_product_attribute}_{$id_customization}_{$product.id_address_delivery|intval}"/>
    		<a
    			id="cart_quantity_up_{$product.id_product}_{$product.id_product_attribute}_{$id_customization}_{$product.id_address_delivery|intval}"
    			class="cart_quantity_up btn btn-default button-plus"
    			{*href="{$link->getPageLink('cart', true, NULL, "add=1&id_product={$product.id_product|intval}&ipa={$product.id_product_attribute|intval}&id_address_delivery={$product.id_address_delivery}&id_customization={$id_customization}&token={$token_cart}")|escape:'html':'UTF-8'}"*}
    			rel="nofollow"
    			title="{l s='Add'}">
    			<span><i class="icon-plus"></i></span>
    		</a>
            
    </div>
    <div>
		{if (!$PS_CATALOG_MODE AND ((isset($product.show_price) && $product.show_price) || (isset($product.available_for_order) && $product.available_for_order)))}
            {if isset($product_in_cart) && isset($product_in_cart.price) && $product_in_cart}
                <span class="price">{l s='=' mod='incartquantity'}{convertPrice price=$product_in_cart.price|floatval*$product_in_cart.cart_quantity}</span>
            {else}
                <span class="price" style="display:none;">{l s='=' mod='incartquantity'}</span>
            {/if}
            
		{/if}
    </div>
</div>

<!-- /InCartQuantity module -->
{strip}
{addJsDef currencySign=$currencySign|html_entity_decode:2:"UTF-8"}
{addJsDef currencyRate=$currencyRate|floatval}
{addJsDef currencyFormat=$currencyFormat|intval}
{addJsDef currencyBlank=$currencyBlank|intval}
{addJsDef deliveryAddress=$cart->id_address_delivery|intval}
{addJsDefL name=txtProduct}{l s='product' js=1}{/addJsDefL}
{addJsDefL name=txtProducts}{l s='products' js=1}{/addJsDefL}
{addJsDefL name=txtEquals}{l s='=' js=1}{/addJsDefL}
{/strip}
Edited by [email protected] (see edit history)
Link to comment
Share on other sites

Первое что бросается в глаза - зачем вам в этом модуле выводить свой $product, который выводится в цикле до этого в шаблоне product_list.tpl?

Link to comment
Share on other sites

Первое что бросается в глаза - зачем вам в этом модуле выводить свой $product, который выводится в цикле до этого в шаблоне product_list.tpl?

 

Я че т не подумал об этом даже. То есть я либо использую $product из product-list.tpl или свой но не с именованием product. Вы это имеете в виду?

Link to comment
Share on other sites

да, смысл модуля получить какое-то дополнительное поле для вывода, product уже есть он вам в хук передаётся, зачем его обратно возвращать

Link to comment
Share on other sites

да, смысл модуля получить какое-то дополнительное поле для вывода, product уже есть он вам в хук передаётся, зачем его обратно возвращать

 

так ведь я на сколько понимаю в хук параметры ($product) передаются через одноименную ему функцию в переменной $params, а не прямо в .tpl модуля. Я пробовал не передавать из модуля $product, и в шаблоне в итоге $product = NULL. То есть все равно через функцию hookDisplayProductListReviews($params), потом в шаблон и т.п.

 

Разве что попробую переименовать $product в своем модуле в $product_2 на случай вдруг они конфликтуют.

Edited by [email protected] (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...