表示機能ラベル- magento 2


製品の詳細ページとサイト内のすべての製品リストのセクションに製品ラベルを表示する要求がある場合は、次のようになります.
リストのセクション
  • 製品詳細ページ-製品内容域(CatalogCount ProductCrown . xml)
  • カテゴリーページ(CatalogRadioCatalorRange . xml)
  • ページビルダーの製品ウィジェット
  • Upsellと関連する製品(CatalogCount ProductCrown . xml)
  • crossell ( CheckOuttle CartCount index . xml )
  • 検索(カタログ検索結果index . xml )
  • アドバンスサーチ(カタログ検索)
    カスタム属性を作成する
    アプリケーション/コード/ベンダー/特徴/セットアップ/パッチ/データ/addFeaturedLabProductAttribute.PHP
    namespace Vendor\FeaturedLabel\Setup\Patch\Data;
    
    use Magento\Catalog\Model\Product;
    use Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend;
    use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
    use Magento\Eav\Setup\EavSetup;
    use Magento\Eav\Setup\EavSetupFactory;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    use Magento\Framework\Setup\Patch\DataPatchInterface;
    use Magento\Framework\Setup\Patch\PatchRevertableInterface;
    
    class AddFeaturedLabelProductAttribute implements DataPatchInterface, PatchRevertableInterface
    {
        /**
         * @var ModuleDataSetupInterface
         */
        private $moduleDataSetup;
        /**
         * @var EavSetupFactory
         */
        private $eavSetupFactory;
    
        /**
         * Constructor
         *
         * @param ModuleDataSetupInterface $moduleDataSetup
         * @param EavSetupFactory $eavSetupFactory
         */
        public function __construct(
            ModuleDataSetupInterface $moduleDataSetup,
            EavSetupFactory $eavSetupFactory
        ) {
            $this->moduleDataSetup = $moduleDataSetup;
            $this->eavSetupFactory = $eavSetupFactory;
        }
    
        /**
         * {@inheritdoc}
         */
        public function apply()
        {
            $this->moduleDataSetup->getConnection()->startSetup();
            /** @var EavSetup $eavSetup */
            $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
            $eavSetup->addAttribute(
                Product::ENTITY,
                'featured_label',
                [
                    'type' => 'int',
                    'label' => 'Featured Label',
                    'input' => 'select',
                    'source' => '',
                    'required' => false,
                    'backend' => ArrayBackend::class,
                    'sort_order' => '30',
                    'global' => ScopedAttributeInterface::SCOPE_STORE,
                    'default' => null,
                    'visible' => true,
                    'user_defined' => true,
                    'searchable' => true,
                    'filterable' => true,
                    'comparable' => false,
                    'visible_on_front' => false,
                    'unique' => false,
                    'apply_to' => '',
                    'group' => 'General',
                    'used_in_product_listing' => true,
                    'is_used_in_grid' => true,
                    'is_visible_in_grid' => false,
                    'is_filterable_in_grid' => false,
                    'option' => ''
                ]
            );
    
            $this->moduleDataSetup->getConnection()->endSetup();
        }
    
        public function revert()
        {
            $this->moduleDataSetup->getConnection()->startSetup();
            /** @var EavSetup $eavSetup */
            $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
            $eavSetup->removeAttribute(Product::ENTITY, 'featured_label');
    
            $this->moduleDataSetup->getConnection()->endSetup();
        }
    
        /**
         * {@inheritdoc}
         */
        public function getAliases()
        {
            return [];
        }
    
        /**
         * {@inheritdoc}
         */
        public static function getDependencies()
        {
            return [
    
            ];
        }
    }
    
    ラベルを表示する1つのテンプレートを作成する
    アプリケーション/コード/ベンダー/特徴/ラベル/フロントエンド/テンプレート/製品/特徴的なラベル.京大理
    /** @var $block \Magento\Catalog\Block\Product\View */
    /* @var $product Vendor\FeaturedLabel\ViewModel\Product */
    /* @var $featuredLabel Vendor\FeaturedLabel\ViewModel\FeaturedLabel */
    
    $product = $block->getData('product');
    $featuredLabel = $block->getData('featured_label_widget');
    ?>
    <?php $currentProduct = $product->getCurrentProduct() ?: $product; ?>
    
    <?php if ($featuredLabel->getFeaturedLabel($currentProduct)): ?>
        <div class="featured-label">
            <?= $block->escapeHtml(__($featuredLabel->getFeaturedLabel($currentProduct))) ?>
        </div>
    <?php endif; ?>
    
    ラベルのビューモデルを作成する
    注:現在の製品は、製品intefaceとして渡されます
    アプリケーション/コード/ベンダー/featuredlabel/viewmodel/featuredlabel.PHP
    namespace Vendor\FeaturedLabel\ViewModel;
    
    use Magento\Catalog\Api\Data\ProductInterface;
    use Magento\Framework\View\Element\Block\ArgumentInterface;
    
    class FeaturedLabel implements ArgumentInterface
    {
        /**
         * @param ProductInterface $product
         * @return false|\Magento\Framework\Phrase
         */
        public function getFeaturedLabel(ProductInterface $product)
        {
            if ($product->getAttributeText('featured_label')) {
                return $product->getAttributeText('featured_label');
            } 
    }
    
    4 )現在の製品を取得するビューモデル
    アプリケーション/コード/ベンダー/カタログ/ViewModel/製品.PHP
    namespace Vendor\Catalog\ViewModel;
    
    use Magento\Catalog\Api\Data\ProductInterface;
    use Magento\Framework\Registry;
    use Magento\Framework\View\Element\Block\ArgumentInterface;
    
    class Product implements ArgumentInterface
    {
        /**
         * @var Registry
         */
        private $registry;
    
        /**
         * @var ProductInterface
         */
        private $product;
    
        public function __construct(
            Registry $registry,
            array $data = []
        ) {
            $this->registry = $registry;
        }
    
        public function getCurrentProduct(): ProductInterface
        {
            if (is_null($this->product)) {
                $this->product = $this->registry->registry('current_product');
            }
            return $this->product;
        }
    }
    
    製品の詳細ページにラベルを追加-製品コンテンツエリア、Upsell、関連製品
    アプリケーション/コード/ベンダー/特徴/ラベル/フロント/レイアウト/CatalogCard productviewビュー.XML
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="product.info.media">
                <block class="Magento\Catalog\Block\Product\View"
                       name="product.featured.label"
                       template="Vendor_FeaturedLabel::product/featured_label.phtml"
                       before="-">
                    <arguments>
                        <argument name="product" xsi:type="object">Vendor\FeaturedLabel\ViewModel\Product</argument>
                        <argument name="featured_label_widget" xsi:type="object">Vendor\FeaturedLabel\ViewModel\FeaturedLabel</argument>
                    </arguments>
                </block>
            </referenceContainer>
    
            <referenceBlock name="catalog.product.related" template="Magento_Catalog::product/list/items.phtml">
                <block name="product.related.featured.label"
                       as="featured.label"
                       template="Vendor_FeaturedLabel::product/featured_label.phtml">
                    <arguments>
                        <argument name="product" xsi:type="object">Vendor\FeaturedLabel\ViewModel\Product</argument>
                        <argument name="featured_label_widget" xsi:type="object">Vendor\FeaturedLabel\ViewModel\FeaturedLabel</argument>
                    </arguments>
                </block>
            </referenceBlock>
    
            <referenceBlock name="product.info.upsell" template="Magento_Catalog::product/list/items.phtml">
                <block name="product.upsell.featured.label"
                       as="featured.label"
                       template="Vendor_FeaturedLabel::product/featured_label.phtml">
                    <arguments>
                        <argument name="product" xsi:type="object">Vendor\FeaturedLabel\ViewModel\Product</argument>
                        <argument name="featured_label_widget" xsi:type="object">Vendor\FeaturedLabel\ViewModel\FeaturedLabel</argument>
                    </arguments>
                </block>
            </referenceBlock>
        </body>
    </page>
    
    6 )カテゴリページのアプリ/コード/ベンダー/featuredlabel/ビュー/フロント/レイアウト/CatalogRadiesカテゴリ.XML
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="category.products.list" template="Vendor_Catalog::product/list.phtml">
                <block name="category.product.featured.label"
                       as="featured.label"
                       template="Vendor_FeaturedLabel::product/featured_label.phtml">
                    <arguments>
                        <argument name="product" xsi:type="object">Vendor\Catalog\ViewModel\Product</argument>
                        <argument name="featured_label_widget" xsi:type="object">Vendor\FeaturedLabel\ViewModel\FeaturedLabel</argument>
                    </arguments>
                </block>
            </referenceBlock>
        </body>
    </page>
    
    ページビルダー製品ウィジェット
    アプリケーション/コード/ベンダー/カタログ/ブロック/製品/productslist.PHP
    namespace Vendor\Catalog\Block\Product;
    
    use Magento\Catalog\Api\CategoryRepositoryInterface;
    use Magento\Catalog\Api\Data\ProductInterface;
    use Magento\Catalog\Block\Product\Context as ProductContext;
    use Magento\Catalog\Model\Product\Visibility;
    use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
    use Magento\CatalogWidget\Block\Product\ProductsList as DefaultProductsList;
    use Magento\CatalogWidget\Model\Rule;
    use Magento\Framework\App\Http\Context;
    use Magento\Framework\DataObject\IdentityInterface;
    use Magento\Framework\Serialize\Serializer\Json;
    use Magento\Framework\Url\EncoderInterface;
    use Magento\Framework\View\Element\BlockInterface;
    use Magento\Framework\View\LayoutFactory;
    use Magento\Rule\Model\Condition\Sql\Builder;
    use Magento\Widget\Block\BlockInterface as WidgetBlockInterface;
    use Magento\Widget\Helper\Conditions;
    
    class ProductsList extends DefaultProductsList implements WidgetBlockInterface, IdentityInterface
    {
        /**
         * @var LayoutFactory
         */
        private $layoutFactory;
    
        /**
         * @var Json
         */
        private $json;
    
        /**
         * @var EncoderInterface
         */
        private $urlEncoder;
    
        /**
         * @var array
         */
        private $layoutBlocks = [];
    
        /**
         * ProductsList constructor.
         * @param ProductContext $context
         * @param CollectionFactory $productCollectionFactory
         * @param Visibility $catalogProductVisibility
         * @param Context $httpContext
         * @param Builder $sqlBuilder
         * @param Rule $rule
         * @param Conditions $conditionsHelper
         * @param CategoryRepositoryInterface $categoryRepository
         * @param LayoutFactory $layoutFactory
         * @param Json $json
         * @param EncoderInterface $urlEncoder
         * @param array $data
         */
        public function __construct(
            ProductContext $context,
            CollectionFactory $productCollectionFactory,
            Visibility $catalogProductVisibility,
            Context $httpContext,
            Builder $sqlBuilder,
            Rule $rule,
            Conditions $conditionsHelper,
            CategoryRepositoryInterface $categoryRepository,
            LayoutFactory $layoutFactory,
            Json $json,
            EncoderInterface $urlEncoder,
            array $data = []
        ) {
            $this->layoutFactory = $layoutFactory;
            $this->json = $json;
            $this->urlEncoder = $urlEncoder;
    
            parent::__construct(
                $context,
                $productCollectionFactory,
                $catalogProductVisibility,
                $httpContext,
                $sqlBuilder,
                $rule,
                $conditionsHelper,
                $categoryRepository,
                $data,
                $json,
                $layoutFactory,
                $urlEncoder
            );
        }
    
        /**
         * @param $name
         * @return mixed|null
         * @throws \Magento\Framework\Exception\LocalizedException
         */
        public function getBlockFromLayout($name)
        {
            $layoutBlock = isset($this->layoutBlocks[$name]) ? $this->layoutBlocks[$name] : null;
    
            if (!$layoutBlock) {
                $layout = $this->layoutFactory->create(['cacheable' => false]);
                $layout->getUpdate()->addHandle('catalog_widget_product_list')->load();
                $layout->generateXml();
                $layout->generateElements();
                $layoutBlock = $layout->getBlock($name);
                $this->layoutBlocks[$name] = $layoutBlock;
            }
    
            return $layoutBlock;
        }
    }
    
    アプリケーション/コード/ベンダー/特徴/ラベル/etc/widget.XML
    <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
        <widget id="products_list" class="Vendor\Catalog\Block\Product\ProductsList">
            <label translate="true">Catalog Products List</label>
            <description translate="true">List of Products</description>
        </widget>
    </widgets>
    
    アプリケーション/コード/ベンダー/特徴/表示/adminhtml/ウェブ/js/内容タイプ/製品/質量コンバーター/カルーセル装置指令.js
    define([
        'Magento_PageBuilder/js/content-type/products/mass-converter/carousel-widget-directive',
        'Magento_PageBuilder/js/utils/object'
    ], function (OriginalCarouselWidgetDirective, _object) {
        'use strict';
    
        function CarouselWidgetDirective() {
            OriginalCarouselWidgetDirective.apply(this, arguments);
        }
    
        CarouselWidgetDirective.prototype = Object.create(OriginalCarouselWidgetDirective.prototype);
    
        /**
         * Override the toDom function to pass new 'type' and 'template' parameters.
         *
         * @param data
         * @param config
         * @returns {*}
         */
        CarouselWidgetDirective.prototype.toDom = function toDom(data, config) {
            var attributes = {
                type: "Vendor\\Catalog\\Block\\Product\\ProductsList",
                template: "Vendor_FeaturedLabel::product/widget/content/carousel.phtml",
                anchor_text: "",
                id_path: "",
                show_pager: 0,
                products_count: data.carousel_products_count,
                condition_option: data.condition_option,
                condition_option_value: "",
                type_name: "Catalog Products Carousel",
                conditions_encoded: this.encodeWysiwygCharacters(data.conditions_encoded || "")
            };
    
            if (data.sort_order) {
                attributes.sort_order = data.sort_order;
            }
    
            if (typeof data[data.condition_option] === "string") {
                attributes.condition_option_value = this.encodeWysiwygCharacters(data[data.condition_option]);
            }
    
            if (attributes.conditions_encoded.length === 0) {
                return data;
            }
    
            _object.set(data, config.html_variable, this.buildDirective(attributes));
            return data;
        };
    
        return CarouselWidgetDirective;
    });
    
    アプリケーション/コード/ベンダー/特徴/表示/adminhtml/web/js/コンテンツタイプ/製品/質量コンバータ/ウィジェット指令.js
    define([
        'Magento_PageBuilder/js/content-type/products/mass-converter/widget-directive',
        'Magento_PageBuilder/js/utils/object'
    ], function (OriginalWidgetDirective, _object) {
        'use strict';
    
        function WidgetDirective() {
            OriginalWidgetDirective.apply(this, arguments);
        }
    
        WidgetDirective.prototype = Object.create(OriginalWidgetDirective.prototype);
    
        /**
         * Override the toDom function to pass new 'type' and 'template' parameters.
         *
         * @param data
         * @param config
         * @returns {*}
         */
        WidgetDirective.prototype.toDom = function toDom(data, config) {
            var attributes = {
                type: "Vendor\\Catalog\\Block\\Product\\ProductsList",
                template: "Vendor_FeaturedLabel::product/widget/content/grid.phtml",
                anchor_text: "",
                id_path: "",
                show_pager: 0,
                products_count: data.products_count,
                condition_option: data.condition_option,
                condition_option_value: "",
                type_name: "Catalog Products List",
                conditions_encoded: this.encodeWysiwygCharacters(data.conditions_encoded || "")
            };
    
            if (data.sort_order) {
                attributes.sort_order = data.sort_order;
            }
    
            if (typeof data[data.condition_option] === "string") {
                attributes.condition_option_value = this.encodeWysiwygCharacters(data[data.condition_option]);
            }
    
            if (attributes.conditions_encoded.length === 0) {
                return data;
            }
    
            _object.set(data, config.html_variable, this.buildDirective(attributes));
            return data;
        };
    
        return WidgetDirective;
    });
    
    アプリケーション/コード/ベンダー/特徴/ラベル/adminhtml/pagebuilder/contentstraタイプ/製品.XML
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_PageBuilder:etc/content_type.xsd">
        <type name="products">
            <appearances>
                <appearance name="grid">
                    <converters>
                        <converter component="Vendor_FeaturedLabel/js/content-type/products/mass-converter/widget-directive" name="widget_directive">
                            <config>
                                <item name="html_variable" value="html"/>
                            </config>
                        </converter>
                    </converters>
                </appearance>
                <appearance name="carousel">
                    <converters>
                        <converter component="Vendor_FeaturedLabel/js/content-type/products/mass-converter/carousel-widget-directive" name="widget_directive">
                            <config>
                                <item name="html_variable" value="html"/>
                            </config>
                        </converter>
                    </converters>
                </appearance>
            </appearances>
        </type>
    </config>
    
    アプリケーション/コード/ベンダー/特徴/ラベル/フロントエンド/レイアウト/CatalogHand WidgetHard productchenリスト.XML
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <block name="category.products.list.featured.label"
                   as="featured.label.top"
                   template="Vendor_FeaturedLabel::product/featured_label.phtml">
                <arguments>
                    <argument name="product" xsi:type="object">Vendor\Catalog\ViewModel\Product</argument>
                    <argument name="featured_label_widget" xsi:type="object">Vendor\FeaturedLabel\ViewModel\FeaturedLabel</argument>
                </arguments>
            </block>
        </body>
    </page>
    
    8 )テンプレートファイル
  • 製品詳細ページ-製品内容域(CatalogCount ProductCrown . xml)
  • カテゴリーページ(CatalogRadioCatalorRange . xml)
  • ページビルダーの製品ウィジェット
  • Upsellと関連する製品(CatalogCount ProductCrown . xml)
  • crossell ( CheckOuttle CartCount index . xml )
  • 検索(カタログ検索結果index . xml )
  • アドバンスサーチ(カタログ検索)
    カテゴリページ/事前検索/検索-表示/フロント/テンプレート/製品/リスト.京大理
    <?php if ($featuredLabel = $block->getChildBlock('featured.label')): ?>
        <?= /* @noEscape */ $featuredLabel->setData('product', $product)->toHtml() ?>
    <?php endif; ?>
    
    クロスセラー/アップセル及び関連商品リスト
    表示/フロントエンド/テンプレート/製品/リスト/アイテム
    <?php if ($featuredLabel = $block->getChildBlock('featured.label')): ?>
        <?= /* @noEscape */ $featuredLabel->setData('product', $item)->toHtml() ?>
    <?php endif; ?>
    
    ページビルダプロダクトウィジェット( carosal )
    <?php if ($featureLabel = $block->getBlockFromLayout('category.products.list.featured.label')): ?>
        <?= /* @noEscape */ $featureLabel->setData('product', $_item)->toHtml() ?>
    <?php endif; ?>
    
    ページビルダプロダクトウィジェット(グリッド)
    <?php if ($featuredLabel = $block->getBlockFromLayout('category.products.list.featured.label')): ?>
        <?= /* @noEscape */ $featuredLabel->setData('product', $_item)->toHtml() ?>
    <?php endif; ?>