Jump to content

Display Products in Random order on my module


okzion

Recommended Posts

Hello all,

in first time sorry for my bad english.

I don't really know where I can ask my quetion. I have a code right there :

Actually I saw this :

 

            if($category->getProducts((int)Context::getContext()->language->id, 1) != '') {
                $cat['name'] = $category->name[(int)Context::getContext()->language->id];
                $cat['products'] = $this->prepareBlocksProducts($category->getProducts((int)Context::getContext()->language->id, 1, 10, 'date_add', 'DESC'));
                array_push($categories,$cat);

            }
        }

 

On my home page the product are sort by date. I would like to have this but RANDOMLY.

 

Is this possible, ? can you help ?

 

here the full code.

 

MANY THANKS

Quote

<?php

if (!defined('_PS_VERSION_'))
{
    exit;
}

use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;

class featuredcategory2 extends Module
{
    protected static $cache_products;
    private $templateFile;

    public function __construct()
    {
        $this->name = 'featuredcategory2';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Ishi Technolabs';
        $this->need_instance = 0;

        $this->bootstrap = true;
        parent::__construct();

        $this->displayName = $this->getTranslator()->trans('Featured Category Products 2', array(), 'Module.featuredcategory2.Admin');
        $this->description = $this->getTranslator()->trans('Displays specified products of category on home page.', array(), 'Module.featuredcategory2.Admin');

        $this->templateFile = 'module:featuredcategory2/views/templates/hook/featuredcategory2.tpl';
    }
       

    public function install()
    {
        $this->_clearCache('*');
        Configuration::updateValue('CFEATURED_ID2', '3,6,9');

        if (!parent::install() || !$this->registerHook('header') || !$this->registerHook('addproduct') || !$this->registerHook('updateproduct') || !$this->registerHook('deleteproduct') || !$this->registerHook('categoryUpdate') || !$this->registerHook('displayHomeTab') || !$this->registerHook('displayHomeTabContent') || !$this->registerHook('displayHomeTop') || !$this->registerHook('displayHome') || !$this->registerHook('displayHomeBottom'))
        {
            return false;
        }

        return true;
    }

    public function uninstall()
    {
        $this->_clearCache('*');

        return parent::uninstall();
    }

    public function getContent()
    {
        $output = '';
        $errors = array();
        if (Tools::isSubmit('submitCategoryFeatured'))
        {
            Configuration::updateValue('CFEATURED_ID2', Tools::getValue('CFEATURED_ID2'));
        }

        return $output . $this->renderForm();
    }

    public function prepareBlocksProducts($products)
    {
        $products_for_template = [];
        $assembler = new ProductAssembler($this->context);
        $presenterFactory = new ProductPresenterFactory($this->context);
        $presentationSettings = $presenterFactory->getPresentationSettings();
        $presenter = new ProductListingPresenter(new ImageRetriever($this->context->link), $this->context->link, new PriceFormatter(), new ProductColorsRetriever(), $this->context->getTranslator());
        $products_for_template = [];
        foreach ($products as $rawProduct)
        {
            $products_for_template[] = $presenter->present($presentationSettings, $assembler->assembleProduct($rawProduct), $this->context->language);
        }

        return $products_for_template;
    }

    public function hookdisplayHome($params)
    {
           if (!$this->isCached($this->templateFile, $this->getCacheId(''))) {
            $this->smarty->assign($this->getWidgetVariables());
        }

        return $this->fetch($this->templateFile, $this->getCacheId(''));
    }

    public function getWidgetVariables($hookName = null, array $configuration = array())
    {
        $arr = explode(",", Configuration::get('CFEATURED_ID2'));
        $categories = array();
        foreach ($arr as $value) {
            $category = new Category($value);
            $cat = array();
            
            if($category->getProducts((int)Context::getContext()->language->id, 1) != '') {
                $cat['name'] = $category->name[(int)Context::getContext()->language->id];
                $cat['products'] = $this->prepareBlocksProducts($category->getProducts((int)Context::getContext()->language->id, 1, 10, 'date_add', 'DESC'));
                array_push($categories,$cat);

            }
        }
        return array(
            'categories' => $categories,
        );
    }

    public function hookAddProduct($params)
    {
        $this->_clearCache('*');
    }

    public function hookUpdateProduct($params)
    {
        $this->_clearCache('*');
    }

    public function hookDeleteProduct($params)
    {
        $this->_clearCache('*');
    }

    public function hookCategoryUpdate($params)
    {
        $this->_clearCache('*');
    }

    public function _clearCache($template, $cache_id = null, $compile_id = null)
    {
        parent::_clearCache('featuredcategory2.tpl');
        parent::_clearCache('tab.tpl', 'featuredcategory2-tab');
    }

    public function renderForm()
    {
        $fields_form = array(
            'form' => array(
                'legend' => array(
                    'title' => $this->getTranslator()->trans('Settings', array(), 'Module.featuredcategory2.Admin'),
                    'icon' => 'icon-cogs'
                ),
                'description' => $this->getTranslator()->trans('Select category of products.', array(), 'Module.featuredcategory2.Admin'),
                'input' => array(
                    array(
                        'type' => 'text',
                        'label' => $this->getTranslator()->trans('Category ID', array(), 'Module.featuredcategory2.Admin'),
                        'name' => 'CFEATURED_ID2',
                        'required' => true,
                    ),
                ),
                'submit' => array('title' => $this->getTranslator()->trans('Save', array(), 'Module.featuredcategory2.Admin'),)
            ),
        );

        $helper = new HelperForm();
        $helper->show_toolbar = false;
        $helper->table = $this->table;
        $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
        $helper->default_form_language = $lang->id;
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
        $this->fields_form = array();
        $helper->id = (int)Tools::getValue('id_carrier');
        $helper->identifier = $this->identifier;
        $helper->submit_action = 'submitCategoryFeatured';
        $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->tpl_vars = array(
            'fields_value' => $this->getConfigFieldsValues(),
            'languages' => $this->context->controller->getLanguages(),
            'id_language' => $this->context->language->id
        );
        return $helper->generateForm(array($fields_form));
    }

    public function getConfigFieldsValues()
    {
        return array(
            'CFEATURED_ID2' => Tools::getValue('CFEATURED_ID2', Configuration::get('CFEATURED_ID2')),
        );
    }
}

 

Link to comment
Share on other sites

Use an SQL query instead of a function.

SQL returns 10 randomly selected product ids, category ids, and category names.

eg. 

'SELECT cp.id_category, cp.id_product, cl.name

FROM ' . _DB_PREFIX_ . 'category_product cp

LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cp.id_category = cl.idcategory)

WHERE cp.id_category IN (' . Configuration::get('CFEATURED_ID2') . ')

AND cl.id_lang = ' . $this->context->language->id . '

ORDER BY RAND()

LIMIT 10;'

Link to comment
Share on other sites

Perfect. Thanks for your help.

Where I should replace this ?

 

I just want to have random product

I tried

 

         if($category->getProducts((int)Context::getContext()->language->id, 1) != '') {
                $cat['name'] = $category->name[(int)Context::getContext()->language->id];
                $cat['products'] = $this->prepareBlocksProducts($category->getProducts((int)Context::getContext()->language->id, 1, 10, 'date_add', 'RAND'));
                array_push($categories,$cat);

 

but nothing change

Edited by okzion (see edit history)
Link to comment
Share on other sites

This is just a demonstration of how to work with it.
I will definitely not make a module or edit it for you.
The basis is commenting on functions, etc.

Query:

SELECT cp.id_category, cp.id_product, cl.name AS category_name FROM ps_category_product cp 
LEFT JOIN ps_category_lang cl ON (cp.id_category = cl.id_category) 
WHERE cp.id_category IN (1,2,3,4,5,6,7,8,9) 
AND cl.id_lang = 1 
GROUP BY cp.id_product 
ORDER BY RAND() 
LIMIT 10

Result query:

obrazek.png.41f6b18e399f0597a6b7b4d65c2bf354.png

So you need to process what you have as a result of the query.

$query = 'SELECT cp.id_category, cp.id_product, cl.name AS category_name FROM ps_category_product cp 
LEFT JOIN ps_category_lang cl ON (cp.id_category = cl.id_category) 
WHERE cp.id_category IN ('.Configuration::get('CFEATURED_ID2').') 
AND cl.id_lang = '.$this->context->language->id.' 
GROUP BY cp.id_product 
ORDER BY RAND() 
LIMIT 10';

$result = Db::getInstance()->execteS($query);

$categories = array();

foreach ($result as $data){
	$categories[] = array(
		'categories' => array(
			'id_category' => $data['id_category'], 
			'id_product' => $data['id_product'], 
			'category_name' => $data['category_name']
		)
	);
}

return $categories;

 

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...