Автор Тема: Добиваю модуль желаемых товаров, нужна помощь  (Прочитано 536 раз)

09 Апрель 2021, 13:23:15
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
есть фронт контролер
<?php




class FavoriteProductsProductsModuleFrontController extends ProductListingFrontController
{


    

    public function 
__construct(){
        
parent::__construct();
        
$this->module Module::getInstanceByName("favoriteproducts");

    }
    public 
$module;

    
//public $query;

    //private $idCustomer;

    
public $customerId;

    public function 
setMedia()
    {
        
$this->registerStylesheet(
            
'front-controller-module',
            
'modules/' $this->module->name '/views/css/front/favoriteproducts-list.css',
            [
                
'media' => 'all',
                
'priority' => 1000,
            ]
        );

        
$this->registerJavascript(
            
'front-controller-module',
            
'modules/' $this->module->name '/views/js/front/ajax/ajax_favoriteproducts_list.js',
            [
                
'position' => 'bottom',
                
'priority' => 1000,
            ]
        );

        
$this->registerJavascript(
            
'front-controller-module-del',
            
'modules/' $this->module->name '/views/js/front/ajax/ajax_favoriteproducts_del.js',
            [
                
'position' => 'bottom',
                
'priority' => 1000,
            ]
        );

        
$this->registerJavascript(
            
'front-controller-module-buy',
            
'modules/' $this->module->name '/views/js/front/ajax/ajax_favoriteproducts_buy.js',
            [
                
'position' => 'bottom',
                
'priority' => 1000,
            ]
        );

        return 
parent::setMedia();
    }


    
//public function checkAccess()
    //    {
    //        return true;
    //    }


    
public function initContent()
    {

        
parent::initContent();
        
        
//if ($this->customerId->checkAccess($this->context->customerId->id)) {
            
$this->doProductSearch(
                
'catalog/listing/id',
                [
                    
'entity' => 'id',
                    
'products' => $result->getProducts()
                ]
            );
        
//}


        
if (Context::getContext()->customer->logged) {
            
$admin false;
            
$customerShow true;
            
$id_customer = (int)$this->context->customer->id;
            
$db Db::getInstance();
            
$id_shop = (int)Context::getContext()->shop->id;
            
$sql = new DbQuery();
            
$sql->select('id_product');
            
$sql->from('favorite_products''c');
            
$sql->where('c.id_customer = ' . (int)$id_customer);
            
$sql->where('c.id_shop = ' . (int)$id_shop);
            
$sql->innerJoin('customer''pa''c.id_customer = ' . (int)$id_customer);
            
$sql->groupBy('c.id_product');
            
$products $db->executeS($sql);

            
$contextObject $this->context;
            
$this->context->smarty->assign(array(
                
'id' => (int)$contextObject->customer->id,
                
'id_customer' => $id_customer,
                
'first_name' => $contextObject->customer->firstname,
                
'last_name' => $contextObject->customer->lastname,
                
'customerShow' => $customerShow,
                
//'products' => $query,
                
'admin' => $admin,
            ));
            return 
$this->setTemplate("module:favoriteproducts/views/templates/front/products.tpl");
        } else {
            
$this->context->smarty->assign(array(
                
'result' => false,
                
'error' => 'ERROR you need to register',
            ));
            return 
$this->setTemplate("module:favoriteproducts/views/templates/front/show-info.tpl");
        }
    }
    
    public function 
getListingLabel()
    {
    }

    protected function 
getProductSearchQuery()
    {
        
$query = new FavoriteProductSearchQuery();
        
$query
            
->setIdCustomer($this->context->customer->id);
            
        return 
$query;
    }


    protected function 
getDefaultProductSearchProvider()
    {
        return new 
FavoriteCategoryProductSearchProvider(
            
//$this->getTranslator(),
            
$this->customerId
        
);
        
    }
    function 
doProductSearch($template$params = [], $locale null)
    {
    }

    
/**
     * Assigns module template for page content.
     *
     * @param string $template Template filename
     *
     * @throws PrestaShopException
     */
    
public function setTemplate($template$params = [], $locale null)
    {
        if (
strpos($template'module:') === 0) {
            
$this->template $template;
        } else {
            
parent::setTemplate($template$params$locale);
        }
    }
}





в getDefaultProductSearchProvider и getProductSearchQuery  реальзованы класы , их немного переделал

use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrderFactory;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * Responsible of getting products for specific category.
 */
class FavoriteCategoryProductSearchProvider implements ProductSearchProviderInterface
{
    private $customerId;
    private $translator;
    private $category;
    private $sortOrderFactory;

    public function __construct(
        TranslatorInterface $translator
       
    ) {
        $this->translator = $translator;
        $this->customerId;
        $this->sortOrderFactory = new SortOrderFactory($this->translator);
    }


    /**
     * @param ProductSearchContext $context
     * @param ProductSearchQuery $query
     *
     * @return ProductSearchResult
     *
     * @throws \PrestaShopDatabaseException
     */
    public function runQuery(
        FavoriteProductSearchQuery $query
    ) {
   
        $id_customer = $query->getIdCustomer();
   
        $db = Db::getInstance();
        //$id_customer = (int)$this->context->customer->id;
        $request = 'SELECT `id_product` FROM `' . _DB_PREFIX_ . 'favorite_products` WHERE `id_customer` = ". $id_customer ."'  ;
        //$productsCount = 'SELECT `count('id_product')` FROM `' . _DB_PREFIX_ . 'favorite_products` WHERE `id_customer` = ". $id_customer ."';
        $product = $db->executeS($request);
        $productsCount = count($products);

        $result = new ProductSearchResult();

        if (!empty($product)) {
            $result
                ->setProducts($product)
                ->setTotalProductsCount($productsCount);

            $result->setAvailableSortOrders(
                $this->sortOrderFactory->getDefaultSortOrders()
            );
        return $result;
        }
    }
}



class FavoriteProductSearchQuery
{
   
    private $idCustomer;


public function setIdCustomer($idCustomer)
    {
        $this->idCustomer = $idCustomer;

        return $this;
    }

    /**
     * @return string
     */
    public function getIdCustomer()
    {
        return $this->idCustomer;
    }
}


как правильно описать doProductSearch в initConent?


09 Апрель 2021, 13:52:21
Ответ #1
  • Модератор
  • Ветеран
  • *****
  • Сообщений: 86688
  • Репутация: +25428/-0
  • Сообщество PrestaShop
    • Просмотр профиля
public function init()
{
        parent::init();
        $this->doProductSearch('catalog/listing/mytemp');
09 Апрель 2021, 14:28:15
Ответ #2
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
mytemp  ето что , надо путь на свой темплейт, он лежит у мменя в модуле

{extends 'page.tpl'}

{block content}
    <h2>
        {if $customerShow}
            <center>{l s='Hello user '} {$first_name|upper} {$last_name|upper}</center>
            {l s='Your Favorite products '}
        {else}
            <center>{l s='Favorite List For User №'} {$id_customer|upper}</center>
        {/if}
    </h2>
    <br>
   
    {if $products}
       
        {if $customerShow}
            <div class="custom-control custom-checkbox">
                <input type="checkbox" name="checkbox_all[]" id="checkbox_all" value="">
                <label for="checkbox_all" class="checkall btn btn-primary btn-lg">{l s='Checkbox all'}</label>
                <div class="btn btn-primary btn-danger btn-lg" id="delFavoritesProducts">{l s='delete'}</div>
                <div class="btn btn-primary btn-success btn-lg" id="buyFavoritesProducts">{l s='buy'}</div>
            </div>
        {/if}
        <div class="favoriteproducts-wrapper row">
       
       
       
            {foreach $products as $product}
                {block name='product_miniature_item'}
                    <article class="product-miniature js-product-miniature col-lg-3" id="product-{$product.id_product}" data-id-product="{$product.id_product}" data-id-product-attribute="{$product.id_product_attribute}" itemscope itemtype="http://schema.org/Product">
                        <div class="thumbnail-container">
                            {block name='product_thumbnail'}
                                {if $product.cover}
                                    <a href="{$product.url}" class="thumbnail product-thumbnail">
                                        <img src="{$product.cover.bySize.home_default.url}" alt="{if !empty($product.cover.legend)}{$product.cover.legend}{else}{$product.name|truncate:30:'...'}{/if}" data-full-size-image-url="{$product.cover.large.url}" />
                                    </a>
                                {else}
                                    <a href="{$product.url}" class="thumbnail product-thumbnail">
                                        <img src="{$urls.no_picture_image.bySize.home_default.url}" />
                                    </a>
                                {/if}
                            {/block}
               
                            <div class="product-description">
                                {block name='product_name'}
                                    {if $page.page_name == 'index'}
                                        <h3 class="h3 product-title" itemprop="name"><a href="{$product.url}">{$product.name|truncate:30:'...'}</a></h3>
                                    {else}
                                        <h2 class="h3 product-title" itemprop="name"><a href="{$product.url}">{$product.name|truncate:30:'...'}</a></h2>
                                    {/if}
                                {/block}
               
                                {block name='product_price_and_shipping'}
                                    {if $product.show_price}
                                        <div class="product-price-and-shipping">
                                            {if $product.has_discount}
                                                {hook h='displayProductPriceBlock' product=$product type="old_price"}
                           
                                                <span class="sr-only">{l s='Regular price' d='Shop.Theme.Catalog'}</span>
                                                <span class="regular-price">{$product.regular_price}</span>
                                                {if $product.discount_type === 'percentage'}
                                                    <span class="discount-percentage discount-product">{$product.discount_percentage}</span>
                                                {elseif $product.discount_type === 'amount'}
                                                    <span class="discount-amount discount-product">{$product.discount_amount_to_display}</span>
                                                {/if}
                                            {/if}
                       
                                            {if $customerShow}
                                                {hook h='displayProductPriceBlock' product=$product type="before_price"}
                                            {/if}
                       
                                            <span class="sr-only">{l s='Price' d='Shop.Theme.Catalog'}</span>
                                            <span itemprop="price" class="price">{$product.price}</span>
                       
                                            {hook h='displayProductPriceBlock' product=$product type='unit_price'}
                       
                                            {hook h='displayProductPriceBlock' product=$product type='weight'}
                       
                       
                                            {if $customerShow}
                                                <div class="product-quantity clearfix">
                           
                                                    <form action="{$urls.pages.cart}" method="post" id="add-to-cart-or-refresh">
                                                        <input type="hidden" name="token" value="{$static_token}">
                                                        <input type="hidden" name="id_product" value="{$product.id_product}" id="product_page_product_id">
                                                        <input type="hidden" name="id_customization" value="0" id="product_customization_id">
                           
                                                        <div class="add">
                                                            <button class="btn btn-primary add-to-cart" data-button-action="add-to-cart" type="submit">
                                                                <i class="material-icons shopping-cart"></i>
                                                                {l s='Add to cart'}
                                                            </button>
                                                        </div>
                                                    </form>
                                                </div>
                                            {/if}
                                        </div>
                                    {/if}
                                {/block}
               
                                {block name='product_reviews'}
                                    {hook h='displayProductListReviews' product=$product}
                                {/block}
                            </div>
               
                            {block name='product_flags'}
                                <ul class="product-flags">
                                    {foreach from=$product.flags item=flag}
                                        <li class="product-flag {$flag.type}">{$flag.label}</li>
                                    {/foreach}
                                </ul>
                            {/block}
               
                            <div class="highlighted-informations{if !$product.main_variants} no-variants{/if} hidden-sm-down">
                                {block name='quick_view'}
                                    <a class="quick-view" href="#" data-link-action="quickview">
                                        <i class="material-icons search">&#xE8B6;</i> {l s='Quick view' d='Shop.Theme.Actions'}
                                    </a>
                                {/block}
               
                                {block name='product_variants'}
                                    {if $product.main_variants}
                                        {include file='catalog/_partials/variant-links.tpl' variants=$product.main_variants}
                                    {/if}
                                {/block}
                            </div>
                        </div>
                    </article>
                {/block}
            {/foreach}
        </div>
       
        {if $customerShow}
            <div class="custom-control custom-checkbox">
                <div class="btn btn-primary btn-danger btn-lg" id="delAllProducts">{l s='delete all'}</div>
                <div class="btn btn-primary btn-success btn-lg" id="buyAllProducts">{l s='buy all'}</div>
            </div>
            <div class="result">
                <p class="warning">You have deleted all products</p>
            </div>
            <script type='text/javascript'>
                const noSelectItem = "{l s='No items selected'}";
            </script>
        {/if}
    {else}
        <p class="warning">{l s='No favorite products have been determined just yet.'}</p>
    {/if}
    <ul class="footer_links">
        <li class="fleft">
            {if $customerShow}
                <a href="{$link->getPageLink('my-account', true)|escape:'html':'UTF-8'}" class="btn btn-sm btn-primary">{l s='Back to account'}</a>
            {else}
                <button onclick="goBack()" class="btn btn-sm btn-primary">{l s='Back to admin'}</button>
                <script>
                    function goBack() {
                        window.history.back();
                    }
                </script>
            {/if}
        </li>
    </ul>
{/block}
09 Апрель 2021, 14:59:00
Ответ #3
  • Модератор
  • Ветеран
  • *****
  • Сообщений: 86688
  • Репутация: +25428/-0
  • Сообщество PrestaShop
    • Просмотр профиля
$this->setTemplate('module:monModule/views/templates/front/mytemp.tpl');
09 Апрель 2021, 15:57:37
Ответ #4
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
так и есть, только название файла другое


(1/1) ContextErrorException
Notice: Undefined index: products


такая ошибка
10 Апрель 2021, 12:07:13
Ответ #5
  • Ветеран
  • *****
  • Сообщений: 16670
  • Репутация: +14630/-5
  • Сообщество PrestaShop
    • Просмотр профиля
Режим отладки в prestashop включаете внизу сайта откроется Symfony Profiler.
Покажет Request / Response и будет понятно что и где править.
12 Апрель 2021, 13:09:08
Ответ #6
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
class
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrderFactory;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * Responsible of getting products for specific category.
 */
class FavoriteCategoryProductSearchProvider implements ProductSearchProviderInterface
{
    //private $idCustomer;
    private $translator;
   // private $category;
    private $sortOrderFactory;

    public function __construct(
        TranslatorInterface $translator
        //Category $category

    ) {
        //$this->category->$;
        $this->translator = $translator;
        $this->sortOrderFactory = new SortOrderFactory($this->translator);
    }


    /**
     * @param ProductSearchContext $context
     * @param ProductSearchQuery $query
     *
     * @return ProductSearchResult
     *
     * @throws \PrestaShopDatabaseException
     */
    public function runQuery(
        ProductSearchContext $context,
        ProductSearchQuery $query
    ) {
   
        $id_customer = $query->getIdCustomer();
   
        $db = Db::getInstance();
        //$id_customer = (int)$this->context->customer->id;
        $request = 'SELECT `id_product` FROM `' . _DB_PREFIX_ . 'favorite_products` WHERE `id_customer` = ". $id_customer ."'  ;
        //$productsCount = 'SELECT `count('id_product')` FROM `' . _DB_PREFIX_ . 'favorite_products` WHERE `id_customer` = ". $id_customer ."';
        $productId = $db->executeS($request);
        $productsCount = count($productId);

        $result = new ProductSearchResult();

        if (!empty($productId)) {
            $result
                ->setProducts($productId)
                ->setTotalProductsCount($productsCount);

            // $result->setAvailableSortOrders(
            //     $this->sortOrderFactory->getDefaultSortOrders()
            // );


        return $result;
        }
    }
}

 controller
<?php

require_once(_PS_MODULE_DIR_ 'favoriteproducts/classes/FavoriteCategoryProductSearchProvider.php');
require_once(
_PS_MODULE_DIR_ 'favoriteproducts/classes/FavoriteProductSearchQuery.php');


class 
FavoriteProductsProductsModuleFrontController extends ProductListingFrontController
{


    

    public function 
__construct(){
        
parent::__construct();
        
$this->module Module::getInstanceByName("favoriteproducts");

    }
    public 
$module;

    
//public $query;

    //private $idCustomer;

    
public $customerId;

    public function 
setMedia()
    {
        
$this->registerStylesheet(
            
'front-controller-module',
            
'modules/' $this->module->name '/views/css/front/favoriteproducts-list.css',
            [
                
'media' => 'all',
                
'priority' => 1000,
            ]
        );

        
$this->registerJavascript(
            
'front-controller-module',
            
'modules/' $this->module->name '/views/js/front/ajax/ajax_favoriteproducts_list.js',
            [
                
'position' => 'bottom',
                
'priority' => 1000,
            ]
        );

        
$this->registerJavascript(
            
'front-controller-module-del',
            
'modules/' $this->module->name '/views/js/front/ajax/ajax_favoriteproducts_del.js',
            [
                
'position' => 'bottom',
                
'priority' => 1000,
            ]
        );

        
$this->registerJavascript(
            
'front-controller-module-buy',
            
'modules/' $this->module->name '/views/js/front/ajax/ajax_favoriteproducts_buy.js',
            [
                
'position' => 'bottom',
                
'priority' => 1000,
            ]
        );

        return 
parent::setMedia();
    }


    
//public function checkAccess()
    //    {
    //        return true;
    //    }


    
public function initContent()
    {

        
parent::initContent();
        
        
//if ($this->category->checkAccess($this->context->category->id)) {
            // $this->doProductSearch(
            //     'module:favoriteproducts/views/templates/front/products'
            //     //[
            //     //    'entity' => 'id',
            //     //    'id' => 'id', 
            //     //]
            // );
        //}


        
if (Context::getContext()->customer->logged) {
            
$admin false;
            
$customerShow true;
            
$id_customer = (int)$this->context->customer->id;
            
$db Db::getInstance();
            
$id_shop = (int)Context::getContext()->shop->id;
            
$sql = new DbQuery();
            
$sql->select('id_product');
            
$sql->from('favorite_products''c');
            
$sql->where('c.id_customer = ' . (int)$id_customer);
            
$sql->where('c.id_shop = ' . (int)$id_shop);
            
$sql->innerJoin('customer''pa''c.id_customer = ' . (int)$id_customer);
            
$sql->groupBy('c.id_product');
            
$products $db->executeS($sql);

            
$contextObject $this->context;
            
$this->context->smarty->assign(array(
                
'id' => (int)$contextObject->customer->id,
                
'id_customer' => $id_customer,
                
'first_name' => $contextObject->customer->firstname,
                
'last_name' => $contextObject->customer->lastname,
                
'customerShow' => $customerShow,
                
//'products' => $query,
                
'admin' => $admin,
            ));

            
print_r($this->getProductSearchVariables());
            exit;
            
//return $this->setTemplate('module:favoriteproducts/views/templates/front/mytemp.tpl');
            
return $this->setTemplate("module:favoriteproducts/views/templates/front/products.tpl");
        } else {
            
$this->context->smarty->assign(array(
                
'result' => false,
                
'error' => 'ERROR you need to register',
            ));
            return 
$this->setTemplate("module:favoriteproducts/views/templates/front/show-info.tpl");
        }
    }
    
    public function 
getListingLabel()
    {
    }

    protected function 
getProductSearchQuery()
    {
        
$query = new FavoriteProductSearchQuery();
        
$query
            
->setIdCustomer($this->context->customer->id);
            
        return 
$query;
    }


    protected function 
getDefaultProductSearchProvider()
    {
        return new 
FavoriteCategoryProductSearchProvider(
            
$this->getTranslator()
            
//$this->category

        
);
        
    }
    function 
doProductSearch($template$params = [], $locale null)
    {
    }

    
/**
     * Assigns module template for page content.
     *
     * @param string $template Template filename
     *
     * @throws PrestaShopException
     */
    
public function setTemplate($template$params = [], $locale null)
    {
        if (
strpos($template'module:') === 0) {
            
$this->template $template;
        } else {
            
parent::setTemplate($template$params$locale);
        }
    }
}







такая ошыбка , как исправить кнонить знает?
12 Апрель 2021, 20:24:48
Ответ #7
  • Ветеран
  • *****
  • Сообщений: 1808
  • Репутация: +49/-1
  • Сообщество PrestaShop
    • Просмотр профиля
такая ошыбка , как исправить кнонить знает?
Какая ошибка? Зачем код, если нет описания ошибки?
13 Апрель 2021, 09:15:20
Ответ #8
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
Цитировать
Какая ошибка? Зачем код, если нет описания ошибки?

 мой касяк


FatalThrowableError
Call to a member function getCurrentSortOrder() on null



вот
13 Апрель 2021, 11:05:54
Ответ #9
  • Партнер
  • Ветеран
  • ****
  • Сообщений: 22816
  • Репутация: +17143/-1
  • Разработка веб-сайтов и веб-программирование
    • Просмотр профиля
Переменные сортироки определите $orderBy, $orderWay ...
Интернет-магазин под ключ.
Какой выбрать движок для интернет магазина ?
Какой движок лучше ?
Magento или Prestashop ?
Решение всех Ваших вопросов в создании Интернет-магазина.