Jump to content

Comment afficher des produits d'une catégorie ?


Recommended Posts

Bonjour, 
J'essaies d'afficher tout les produits correspondants a une catégorie, a la place des produits complémentaires. Exemple, je suis sur la page des cahier et je souhaites afficher toute la catégorie stylo mais seulement les bleus. (Les produits ont déjà leurs catégorie) et j'utilises actuellement ce code :

{foreach from=$subcategories item="subcategory"}
  {block name='category_miniature'}
 	 {include file='catalog/_partials/miniatures/subcategory.tpl' subcategory=$subcategory}
  {/block}
{/foreach}

mais a ce que j'ai compris, je n'ai pas la variable $subcategories d'initialisée. Ma question est donc la suivante sachant que je travailles sur ce dossier :

templates\catalog\product.tpl

Où dois-je rajouter, et surtout quel code, pour que je reçoives le $subcategories de mon product.tpl, mes stylos bleus ? 

merci a vous et bonne journée et bonne année !

Link to comment
Share on other sites

Bonjour,

 

Je suis sur le même problème ! je vends des produits de couture sur-mesure et souhaite afficher des produits selon caractéristiques (pour les chutes de tissu uniquement) 

Avoir une bannière de produits, surement en promotion et sélectionner les produits souhaités

Je suis sur la version 1.7.7.0

Je vous remercie,

Link to comment
Share on other sites

De ce que j'ai chercher apparemment faut faire quelque chose a partir des controllers mais je ne sait pas quelle partie du code rajouter au controller qui gère la page de produit. 

Par la détection est elle même écrite dans le sens ou ça seras toujours les stylos de couleur bleue qui seras affichée avec les cahier. Je sait pas si ça peut aider mais je continues mes recherches de mon coté.

Link to comment
Share on other sites

Ok du coup on se trouve sur une page produit, est ce que c le module produit dans la meme categorie ou accessoire  qui est utilisé ? si c'est accessoire, ben on choisi les produit stylo bleu un par un, on peux aller en bdd pour que ca aille plus vite. Si c le module produits dans la meme categorie on peux effectivement faire des modifs dans le code.

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

je ne connais pas quelle module attaquer en fait et je ne sait pas non plus quoi importer de la bdd pour avoir mes produits en plus que cela j'aimerais vraiment que ça soit dynamique.

mais je confirmes que ça ne concernes pas les accessoires j'aimerais Remplacer cette catégorie en fait par ces fameux stylos bleus en dynamique.

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

Malheureusement, le module partagé ne remplies pas la fonctionnalité souhaitée. J'aimerais en gros que tout mes produits de la catégorie stylo qui ont la caractéristique bleu, peut être afficher a la place des accessoires, et la seule chose qu'il me manques pour ce faire c'est récupérer $subcategorie il me sembles, mais dans le produit... C'est la seule partie qui semble me bloquer...

Link to comment
Share on other sites

Ok du coup je t'ai fais la fonctionnalité:

http://demo1750.baba-agency.com/hommes/1-1-hummingbird-printed-t-shirt.html

je me suis basé sur le code du module ps_featured

1- on crée un override de Category.php /override/classes

<?php
/**
 * 2007-2018 PrestaShop.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2018 PrestaShop SA
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
use PrestaShop\PrestaShop\Adapter\Category\CategoryProductSearchProvider;
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;

class Category extends CategoryCore
{
    public function getProductsByIdCategory($id_category,$nProducts)
    {

        $context = Context::getContext();
        $category = new Category((int)$id_category);

        $searchProvider = new CategoryProductSearchProvider(
            $context->getTranslator(),
            $category
        );

        $context = new ProductSearchContext($context);

        $query = new ProductSearchQuery();

        if ($nProducts < 0) {
            $nProducts = 12;
        }

        $query
            ->setResultsPerPage($nProducts)
            ->setPage(1)
        ;

        if (Configuration::get('HOME_FEATURED_RANDOMIZE')) {
            $query->setSortOrder(SortOrder::random());
        } else {
            $query->setSortOrder(new SortOrder('product', 'position', 'asc'));
        }

        $result = $searchProvider->runQuery(
            $context,
            $query
        );


        $context = Context::getContext();

        $assembler = new ProductAssembler($context);

        $presenterFactory = new ProductPresenterFactory($context);
        $presentationSettings = $presenterFactory->getPresentationSettings();
        $presenter = new ProductListingPresenter(
            new ImageRetriever(
                $context->link
            ),
            $context->link,
            new PriceFormatter(),
            new ProductColorsRetriever(),
            $context->getTranslator()
        );

        $products_for_template = [];

        foreach ($result->getProducts() as $rawProduct) {
            $products_for_template[] = $presenter->present(
                $presentationSettings,
                $assembler->assembleProduct($rawProduct),
                $context->language
            );
        }

        return $products_for_template;
    }
}

2 - dans le product.tpl /themes/classic/templates/catalog/

{* Modif Alex *}
{assign var=productsCustom value=Category::getProductsByIdCategory(6,4)}

  <section class="product-accessories clearfix">
        <p class="h5 text-uppercase">{l s='You might also like' d='Shop.Theme.Catalog'}</p>
          <div class="products">
            {foreach from=$productsCustom item="product_custom"}
              {block name='product_miniature'}
                {include file='catalog/_partials/miniatures/product.tpl' product=$product_custom}
              {/block}
            {/foreach}

          </div>
        </section>
{* Modif Alex *}

Category::getProductsByIdCategory(6,4) le 1er parametre est la categorie qu'on target id 6 dans cet exemple, le deuxieme parametre le nombre de produits que l'on souhaite afficher ici 4

 

cdt

Capture3.JPG

Capture2.JPG

Capture.JPG

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

J'ai oublié le tri par caracteristique...

on va faire une nouvelle fonction getProductsByFeature basé sur getProducts sauf qu on rajoute un parametre de caracteristique

<?php
/**
 * 2007-2018 PrestaShop.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2018 PrestaShop SA
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

use PrestaShop\PrestaShop\Core\Module\WidgetInterface;
use PrestaShop\PrestaShop\Adapter\Category\CategoryProductSearchProvider;
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;

class Category extends CategoryCore
{
    public function getProductsByIdCategory($id_category,$nProducts,$id_feature)
    {

        $context = Context::getContext();
        $category = new Category((int)$id_category);

        $searchProvider = new CategoryProductSearchProvider(
            $context->getTranslator(),
            $category
        );

        $context = new ProductSearchContext($context);

        $query = new ProductSearchQuery();

        if ($nProducts < 0) {
            $nProducts = 12;
        }

        $query
            ->setResultsPerPage($nProducts)
            ->setPage(1)
        ;

        if (Configuration::get('HOME_FEATURED_RANDOMIZE')) {
            $query->setSortOrder(SortOrder::random());
        } else {
            $query->setSortOrder(new SortOrder('product', 'position', 'asc'));
        }

        $result = $searchProvider->runQuery(
            $context,
            $query
        );


        $context = Context::getContext();

        $assembler = new ProductAssembler($context);

        $presenterFactory = new ProductPresenterFactory($context);
        $presentationSettings = $presenterFactory->getPresentationSettings();
        $presenter = new ProductListingPresenter(
            new ImageRetriever(
                $context->link
            ),
            $context->link,
            new PriceFormatter(),
            new ProductColorsRetriever(),
            $context->getTranslator()
        );

        $products_for_template = [];

        foreach (Category::getProductsByFeature($id_category,$id_feature,1,1,$nProducts) as $rawProduct) {
            $products_for_template[] = $presenter->present(
                $presentationSettings,
                $assembler->assembleProduct($rawProduct),
                $context->language
            );
        }

        return $products_for_template;
    }

    public function getProductsByFeature(
        $id_category,
        $id_feature,
        $idLang,
        $p,
        $n,
        $orderyBy = null,
        $orderWay = null,
        $getTotal = false,
        $active = true,
        $random = false,
        $randomNumberProducts = 1,
        $checkAccess = true,
        Context $context = null
        
    ) {
        if (!$context) {
            $context = Context::getContext();
        }

      
        $front = in_array($context->controller->controller_type, array('front', 'modulefront'));
        $idSupplier = (int) Tools::getValue('id_supplier');

        /* Return only the number of products */
        if ($getTotal) {
            $sql = 'SELECT COUNT(cp.`id_product`) AS total
                    FROM `' . _DB_PREFIX_ . 'product` p
                    ' . Shop::addSqlAssociation('product', 'p') . '
                    LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON p.`id_product` = cp.`id_product`
                    WHERE cp.`id_category` = ' . (int) $this->id .
                ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') .
                ($active ? ' AND product_shop.`active` = 1' : '') .
                ($idSupplier ? 'AND p.id_supplier = ' . (int) $idSupplier : '');

            return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
        }

        if ($p < 1) {
            $p = 1;
        }

        /** Tools::strtolower is a fix for all modules which are now using lowercase values for 'orderBy' parameter */
        $orderyBy = Validate::isOrderBy($orderyBy) ? Tools::strtolower($orderyBy) : 'position';
        $orderWay = Validate::isOrderWay($orderWay) ? Tools::strtoupper($orderWay) : 'ASC';

        $orderByPrefix = false;
        if ($orderyBy == 'id_product' || $orderyBy == 'date_add' || $orderyBy == 'date_upd') {
            $orderByPrefix = 'p';
        } elseif ($orderyBy == 'name') {
            $orderByPrefix = 'pl';
        } elseif ($orderyBy == 'manufacturer' || $orderyBy == 'manufacturer_name') {
            $orderByPrefix = 'm';
            $orderyBy = 'name';
        } elseif ($orderyBy == 'position') {
            $orderByPrefix = 'cp';
        }

        if ($orderyBy == 'price') {
            $orderyBy = 'orderprice';
        }

        $nbDaysNewProduct = Configuration::get('PS_NB_DAYS_NEW_PRODUCT');
        if (!Validate::isUnsignedInt($nbDaysNewProduct)) {
            $nbDaysNewProduct = 20;
        }

        $sql = 'SELECT p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) AS quantity' . (Combination::isFeatureActive() ? ', IFNULL(product_attribute_shop.id_product_attribute, 0) AS id_product_attribute,
                    product_attribute_shop.minimal_quantity AS product_attribute_minimal_quantity' : '') . ', pl.`description`, pl.`description_short`, pl.`available_now`,
                    pl.`available_later`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, image_shop.`id_image` id_image,
                    il.`legend` as legend, m.`name` AS manufacturer_name, cl.`name` AS category_default,
                    DATEDIFF(product_shop.`date_add`, DATE_SUB("' . date('Y-m-d') . ' 00:00:00",
                    INTERVAL ' . (int) $nbDaysNewProduct . ' DAY)) > 0 AS new, product_shop.price AS orderprice
                FROM `' . _DB_PREFIX_ . 'category_product` cp
                LEFT JOIN `' . _DB_PREFIX_ . 'product` p
                    ON p.`id_product` = cp.`id_product`
                ' . Shop::addSqlAssociation('product', 'p') .
                (Combination::isFeatureActive() ? ' LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` product_attribute_shop
                ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) $context->shop->id . ')' : '') . '
                ' . Product::sqlStock('p', 0) . '
                LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl
                    ON (product_shop.`id_category_default` = cl.`id_category`
                    AND cl.`id_lang` = ' . (int) $idLang . Shop::addSqlRestrictionOnLang('cl') . ')
                LEFT JOIN `' . _DB_PREFIX_ . 'product_lang` pl
                    ON (p.`id_product` = pl.`id_product`
                    AND pl.`id_lang` = ' . (int) $idLang . Shop::addSqlRestrictionOnLang('pl') . ')
                LEFT JOIN `' . _DB_PREFIX_ . 'image_shop` image_shop
                    ON (image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop=' . (int) $context->shop->id . ')
                LEFT JOIN `' . _DB_PREFIX_ . 'image_lang` il
                    ON (image_shop.`id_image` = il.`id_image`
                    AND il.`id_lang` = ' . (int) $idLang . ')
                LEFT JOIN `' . _DB_PREFIX_ . 'manufacturer` m
                    ON m.`id_manufacturer` = p.`id_manufacturer`
                LEFT JOIN `' . _DB_PREFIX_ . 'feature_product` fp
                    ON fp.`id_product` = p.`id_product`

                WHERE product_shop.`id_shop` = ' . (int) $context->shop->id . '
                AND fp.`id_feature_value` = ' . (int) $id_feature. '
                    AND cp.`id_category` = ' . (int) $id_category
                    . ($active ? ' AND product_shop.`active` = 1' : '')
                    . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '')
                    . ($idSupplier ? ' AND p.id_supplier = ' . (int) $idSupplier : '');

        if ($random === true) {
            $sql .= ' ORDER BY RAND() LIMIT ' . (int) $randomNumberProducts;
        } else {
            $sql .= ' ORDER BY ' . (!empty($orderByPrefix) ? $orderByPrefix . '.' : '') . '`' . bqSQL($orderyBy) . '` ' . pSQL($orderWay) . '
            LIMIT ' . (((int) $p - 1) * (int) $n) . ',' . (int) $n;
        }

        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql, true, false);

        if (!$result) {
            return array();
        }

        if ($orderyBy == 'orderprice') {
            Tools::orderbyPrice($result, $orderWay);
        }

        // Modify SQL result
        return Product::getProductsProperties($idLang, $result);
    }
}
{* Modif Alex *}
{assign var=productsCustom value=Category::getProductsByIdCategory(6,4,18)}

  <section class="product-accessories clearfix">
        <p class="h5 text-uppercase">{l s='You might also like' d='Shop.Theme.Catalog'}</p>
          <div class="products">
            {foreach from=$productsCustom item="product_custom"}


            <pre>{$product_custom.feature}</pre>
              {block name='product_miniature'}
                {include file='catalog/_partials/miniatures/product.tpl' product=$product_custom}
              {/block}
            {/foreach}

          </div>
        </section>
{* Modif Alex *}

ici on prend 18 comme id_feature value

 

Capture.JPG

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