Автор Тема: не могу правильно написать frontController  (Прочитано 496 раз)

06 Апрель 2021, 10:46:00
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
делаю фронт контролер желаемых товаров  в лк пользователя, проблема, не отображается товар тоесть не могу его найти или чтото такое, чучуть нага*нокодил, посмотрите что не так, где ошыбки или что надо ещо


<?php

class FavoriteProductsProductsModuleFrontController extends ProductListingFrontController
{

    

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

    }
    public 
$module;

    
//public $query;

    
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();
    }

    function 
doProductSearch($template$params = [], $locale null)
        {
            if (
$this->ajax) {
                
ob_end_clean();
                
header('Content-Type: application/json');
                
$this->ajaxRender(json_encode($this->getAjaxProductSearchVariables()));
    
                return;
            } else {
                
$variables $this->getProductSearchVariables();
                
$this->context->smarty->assign([
                    
'listing' => $variables,
                ]);
                
$this->setTemplate($template$params$locale);
            }
        }
    
//public function checkAccess()
    //    {
    //        return true;
    //    }

    
public function initContent()
    {

        
parent::initContent();

        
//if ($this->customerId->checkAccess($this->context->customerId->id)) {
            
$this->doProductSearch(
                
//'catalog/listing/customerId',
                
[
                
//    'entity' => 'customerId',

                    
'id' => $this->customerId->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,
            ));
            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->customerId->id);
        return 
$query;

    }
    protected function 
getDefaultProductSearchProvider()
    {
        return new 
FavoriteCategoryProductSearchProvider(
            
$this->getIdCustomer(),
            
$this->customerId
        
);
    }
    
}





два класа что дописал, чуть изменил добавил  во вложениях
06 Апрель 2021, 12:51:26
Ответ #1
  • Ветеран
  • *****
  • Сообщений: 22125
  • Репутация: +25303/-1
  • Prestashop - просто и эффективно
    • Просмотр профиля
Эксперт Prestashop - решения всех проблем, написание модулей, создание тем для интернет-магазинов под Prestashop.
Эксперт Magento - создам сайт на Magento, программирование кастомных модулей для Magento, кастомизация тем Magento.
Лучшие цены!!!
06 Апрель 2021, 16:17:04
Ответ #2
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
06 Апрель 2021, 20:08:42
Ответ #3
  • Ветеран
  • *****
  • Сообщений: 33325
  • Репутация: +26771/-0
    • Просмотр профиля
Режим отладки в prestashop включите. Проверьте запрос, который формируется при поиске товара.
06 Апрель 2021, 20:57:16
Ответ #4
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
Режим отладки в prestashop включите. Проверьте запрос, который формируется при поиске товара.
ето есть


вот что пишет
(1/1) ClassNotFoundException
Attempted to load class "favoriteProductSearchQuery" from the global namespace.
Did you forget a "use" statement?



ети два класа лежат в папке clesses, которая в корне модуля лежит.
класы немного поменял названия впереди добавил favorite


07 Апрель 2021, 10:46:39
Ответ #5
  • Ветеран
  • *****
  • Сообщений: 33325
  • Репутация: +26771/-0
    • Просмотр профиля
В основной файл модуля
include_once _PS_MODULE_DIR_.'название модуля/FavoriteProductSearchQuery.php.php';
07 Апрель 2021, 11:38:21
Ответ #6
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
В основной файл модуля
include_once _PS_MODULE_DIR_.'название модуля/FavoriteProductSearchQuery.php.php';

в файле где есть новый клас забрал namespace  который вел к основному класу, тогда ,  тогда клас есть


117 строка        'products' => $query,

Notice: Undefined variable: query    - такое пишет

как то неправильно делаю в методах чтоли

<?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/customerId',
                
[
                    
//'entity' => 'id',

                    
'id' => $this->context->customer->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,
            ));
            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->customer->id
        
);
    }
    function 
doProductSearch($template$params = [], $locale null)
    {
    }
}




07 Апрель 2021, 15:36:49
Ответ #7
  • Ветеран
  • *****
  • Сообщений: 1808
  • Репутация: +49/-1
  • Сообщество PrestaShop
    • Просмотр профиля
А где у вас инициализация переменной query в методе initContent?
07 Апрель 2021, 15:48:54
Ответ #8
  • Ветеран
  • *****
  • Сообщений: 33325
  • Репутация: +26771/-0
    • Просмотр профиля
117 строка        'products' => $query,
Notice: Undefined variable: query    - такое пишет

как то неправильно делаю в методах чтоли
$query определена в классе SearchControllerCore.
Ваш класс наследуют методы и переменные класса ProductListingFrontControllerCore, а не SearchControllerCore.
У вас есть объявление переменной
public $query;Но нет инициализации.
07 Апрель 2021, 18:04:22
Ответ #9
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
во вложениях есть где я дописал два класа , чуть их поменял.....
дальше тупик , что как делать не пойму
07 Апрель 2021, 18:58:49
Ответ #10
  • Новичок
  • *
  • Сообщений: 18
  • Репутация: +0/-0
  • Сообщество PrestaShop
    • Просмотр профиля
надо реализовать два sql запроса и их описать в етом методе для дальнейшей роботы

public function runQuery(
        ProductSearchQuery $query
    ) {
        /*$products = $this->getProductsOrCount($context, $query, 'products');
        $count = $this->getProductsOrCount($context, $query, 'count');

        $result = new ProductSearchResult();

        if (!empty($products)) {
            $result
                ->setProducts($products)
                ->setTotalProductsCount($count);

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



        //    $sql = new DbQuery();
        //    $sql->select('id_product');
        //    $sql->from('favorite_products', 'c');
        //    $products = $db->executeS($sql);


        $db = Db::getInstance();
        $request = 'SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer`';
        $productsCount = "SELECT `count('id_favorite_products')` FROM `' . _DB_PREFIX_ . 'favorite_products` ";
        //$idcustomer = $db->executeS($request);
        //$count = $db->getValue($productsCount);

        //$result = new ProductSearchResult();

        if (!empty($idcustomer)) {
            $result
                ->setProducts($idcustomer)
                ->setTotalProductsCount($count);

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

        return $result;
        }
    }



в коментах что было до , и мой го*но код
08 Апрель 2021, 13:04:45
Ответ #11
  • Ветеран
  • *****
  • Сообщений: 3419
  • Репутация: +79/-6
  • Сообщество PrestaShop
    • Просмотр профиля
Таких модулей полно. Возьми за основу оф модуль и делай по нему
https://github.com/PrestaShop/favoriteproducts
08 Апрель 2021, 13:12:43
Ответ #12
  • Фрилансер
  • *
  • Сообщений: 132
  • Репутация: +2/-0
  • Сообщество PrestaShop
    • Просмотр профиля