не могу правильно написать frontController

Автор DimaLishnovskiy, 06 апреля 2021, 10:46:00

« назад - далее »

DimaLishnovskiy

делаю фронт контролер желаемых товаров  в лк пользователя, проблема, не отображается товар тоесть не могу его найти или чтото такое, чучуть нага*нокодил, посмотрите что не так, где ошыбки или что надо ещо



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






два класа что дописал, чуть изменил добавил  во вложениях

PrestaMan

Эксперт Prestashop - решения всех проблем, написание модулей, создание тем для интернет-магазинов под Prestashop.
Эксперт Magento - создам сайт на Magento, программирование кастомных модулей для Magento, кастомизация тем Magento.
Лучшие цены!!!

DimaLishnovskiy


coder

Режим отладки в prestashop включите. Проверьте запрос, который формируется при поиске товара.

DimaLishnovskiy

Цитата: coder от 06 апреля 2021, 20:08:42
Режим отладки в prestashop включите. Проверьте запрос, который формируется при поиске товара.
ето есть


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



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



coder

В основной файл модуля
include_once _PS_MODULE_DIR_.'название модуля/FavoriteProductSearchQuery.php.php';

DimaLishnovskiy

Цитата: coder от 07 апреля 2021, 10:46:39
В основной файл модуля
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)
   {
   }
}






Mr.Sen

А где у вас инициализация переменной query в методе initContent?

coder

Цитата: DimaLishnovskiy от 07 апреля 2021, 11:38:21
117 строка        'products' => $query,
Notice: Undefined variable: query    - такое пишет

как то неправильно делаю в методах чтоли
$query определена в классе SearchControllerCore.
Ваш класс наследуют методы и переменные класса ProductListingFrontControllerCore, а не SearchControllerCore.
У вас есть объявление переменной
public $query;
Но нет инициализации.

DimaLishnovskiy

во вложениях есть где я дописал два класа , чуть их поменял.....
дальше тупик , что как делать не пойму

DimaLishnovskiy

надо реализовать два 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;
        }
    }




в коментах что было до , и мой го*но код

Миколас

Таких модулей полно. Возьми за основу оф модуль и делай по нему
https://github.com/PrestaShop/favoriteproducts

Svan