1

I am looking for a way to individually set the default view for each category.

Fo xample Category Shoes should be Grid and Category T-Shirts should be list view.

I found this for M2 but its not changing anything (1. Option)

https://www.webmoves.net/blog/build/specify-grid-or-list-mode-on-a-per-category-basis-in-magento-3190/

<reference name="product_list_toolbar">
  <action method="setCurrentMode">
    <mode>grid</mode>
  </action>
</reference>
  • where you added above code ? – Pawan Nov 24 '18 at 4:19
  • catalog/categories/cat-xyz/design – Michael Müller Nov 24 '18 at 5:23
  • tutorial and code you are using is for magento 1 – Pawan Nov 24 '18 at 8:47
  • As I see it, the answer by Himmat Paliwal relies on using a modified template file that gets called via xml update per category to generate the product listing. What if I already have a customized template for categories? How do I integrate this solution? – dsmr Nov 26 '18 at 16:21
  • If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review – Rama Chandran M Nov 26 '18 at 17:13
0

You can create custom module to achieve this functionality, Please follow below steps to done with this module:

The code could be downloaded from below link too: https://bitbucket.org/hemant2586/customlistmode/src/905dbde7dadabd655a21ccadfe5baa5378551bfd/MyCompany/CustomListMode/?at=master

Create new module with namespace MyCompany_CustomListMode find the files used below:

  1. etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Company_CustomListMode" setup_version="1.0.0" >
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>
  1. Registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE, 'MyCompany_CustomListMode', __DIR__
);
  1. composer.json
{
    "name": "mycompany/magento2-customlistmode",
    "description": "Guide Demo for module",
    "version": "1.0.0",
    "require": {
        "magento/module-backend": "~100.0.0"
    },
    "type": "magento2-module",
    "extra": {
        "map": [
            [
                "*",
                "MyCompany/CustomListMode"
            ]
        ]
    }
}
  1. Setup/InstallData.php
<?php
namespace MyCompany\CustomListMode\Setup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\InstallDataInterface;
class InstallData implements InstallDataInterface {

    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory) {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
        $setup->startSetup();

        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->addAttribute(
                \Magento\Catalog\Model\Category::ENTITY, 'show_mode', [
                'type' => 'varchar',
                'label' => 'Show Mode',
                'input' => 'select',
                'required' => false,
                'source' => 'W3solver\Customcategorymode\Model\Category\Attribute\Source\Showmode',
                'sort_order' => 102,
                'visible' => true,
                'user_defined' => true,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'Display Settings',
            ]
        );


        $setup->endSetup();
    }

}
  1. Model\Category\Attribute\Source\Attribute.php
<?php
namespace MyCompany\CustomListMode\Model\Category\Attribute\Source;
class Showmode extends 
  \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    public function getAllOptions()`
    `{
        if (!$this->_options) {
            $this->_options = [
                ['value' => \Magento\Catalog\Helper\Product\ProductList::VIEW_MODE_LIST, 'label' => __('List')],
                ['value' => \Magento\Catalog\Helper\Product\ProductList::VIEW_MODE_GRID, 'label' => __('Grid')],
            ];
        }
        return $this->_options;
    }
}
  1. view/frontend/layout/catalog_category_view.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="default.category.products.list" template="MyCompany_CustomListMode::product/list.phtml"/>
    </body>
</page>
  1. view/frontend/templates/product/list.phtml
<?php
use Magento\Framework\App\Action\Action;
$_productCollection = $block->getLoadedProductCollection();
$_helper = $this->helper('Magento\Catalog\Helper\Output');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category
    if($category->getShowMode() == "list"){ 
        $showGrid = 'list'; 
    }else{
        $showGrid = 'grid';
    }
?>
<?php if (!$_productCollection->count()): ?>
    `<div class="message info empty"><div><?php /* @escapeNotVerified */ echo __('We can\'t find products matching the selection.') ?></div></div>
<?php else: ?>
    <?php echo $block->getToolbarHtml() ?>
    <?php echo $block->getAdditionalHtml() ?>
    <?php
    if ($showGrid == 'grid') {
        $viewMode = 'grid';
        $image = 'category_page_grid';
        $showDescription = false;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    } else {
        $viewMode = 'list';
        $image = 'category_page_list';
        $showDescription = true;
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;
    }
    $pos = $block->getPositioned();
    ?>
    <div class="products wrapper <?php /* @escapeNotVerified */ echo $viewMode; ?> products-<?php /* @escapeNotVerified */ echo $viewMode; ?>">
        <?php $iterator = 1; ?>
        <ol class="products list items product-items">
            <?php foreach ($_productCollection as $_product): 
            ?>
                <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="item product product-item">' : '</li><li class="item product product-item">' ?>
                <div class="product-item-info" data-container="product-grid">
                    <?php
                    $productImage = $block->getImage($_product, $image);
                    if ($pos != null) {
                        $position = ' style="left:' . $productImage->getWidth() . 'px;'
                            . 'top:' . $productImage->getHeight() . 'px;"';
                    }
                    ?>
                    <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
                        <?php echo $productImage->toHtml(); ?>
                    </a>
                    <div class="product details product-item-details">
                        <?php
                            $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                        ?>
                        <strong class="product name product-item-name">
                            <a class="product-item-link"
                               href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">
                                <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getName(), 'name'); ?>
                            </a>
                        </strong>
                        <?php echo $block->getReviewsSummaryHtml($_product, $templateType); ?>
                        <?php /* @escapeNotVerified */ echo $block->getProductPrice($_product) ?>
                        <?php echo $block->getProductDetailsHtml($_product); ?>`
                        `<div class="product-sku"> <?php echo $_product->getSku(); ?></div>

                        <div class="product-item-inner">
                            <div class="product actions product-item-actions"<?php echo strpos($pos, $viewMode . '-actions') ? $position : ''; ?>>
                                <div class="actions-primary"<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>
                                    <?php if ($_product->isSaleable()): ?>
                                        <?php $postParams = $block->getAddToCartPostParams($_product);  ?>
                                        <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
                                            <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
                                            <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
                                            <?php echo $block->getBlockHtml('formkey')?>
                                            <button type="submit"
                                                    title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                                                    class="action tocart primary">
                                                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <?php if ($_product->getIsSalable()): ?>
                                            <div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>
                                        <?php else: ?>
                                            <div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                <div data-role="add-to-links" class="actions-secondary"<?php echo strpos($pos, $viewMode . '-secondary') ? $position : ''; ?>>
                                    <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>
                                        <a href="#"
                                           class="action towishlist"
                                           aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                           data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                           data-action="add-to-wishlist"
                                           role="button">
                                            <span class="icon icon-like"></span>
                                            <span class="label"><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                                        </a>
                                    <?php endif; ?>
                                    <?php
                                    $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');
                                    ?>
                                    <a href="#"
                                       class="action tocompare"
                                       aria-label="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                       data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product); ?>'
                                       role="button">
                                       <span class="icon icon-compare"></span>
                                        <span class="label"><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
                                    </a>
                                </div>
                            </div>
                            <?php if ($showDescription):?>
                                <div class="product description product-item-description">
                                    <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php /* @escapeNotVerified */ echo $_productNameStripped ?>"
                                       class="action more"><?php /* @escapeNotVerified */ echo __('Learn More') ?></a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php echo($iterator == count($_productCollection)+1) ? '</li>' : '' ?>
            <?php endforeach; ?>
        </ol>
    </div>
    <?php echo $block->getToolbarHtml() ?>
    <?php if (!$block->isRedirectToCartEnabled()) : ?>
        <script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {}
            }
        }
        </script>
    <?php endif; ?>
<?php endif; ?>
  1. view/adminhtml/ui_component/category_form.xml
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <fieldset name="display_settings">
        <field name="show_mode">
            <argument name="data" xsi:type="array">
            <item name="options" xsi:type="object">MyCompany\CustomListMode\Model\Category\Attribute\Source\Showmode</item>
                <item name="config" xsi:type="array">
                    <item name="sortOrder" xsi:type="number">102</item>
                    <item name="dataType" xsi:type="string">string</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="label" xsi:type="string" translate="true">Show Mode</item>
                </item>
            </argument>
        </field>    
    </fieldset>
</form>

Please follow above steps to create custom module (I have also added the public repo link to download the code directly) and add below layout update xml to required category to get the listing as per the selected list mode:

<referenceContainer name="content">
    <referenceBlock name="category.products.list">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">MyCompany_CustomListMode::product/list.phtml</argument>
        </action>
    </referenceBlock>
</referenceContainer>

enter image description here

Please let me know if you find any issue after implementing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.