1

I use this way to get related product collection

/**
 * Prepare and return product collection
 *
 * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
 */
public function createCollection()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('AntonStudio\StockUpdate\Block\RelatedProducts');

    $currentProduct = $myBlock->getCurrentProduct();
    $relatedProducts = $currentProduct->getRelatedProductCollection();
    /**
     * Prevent retrieval of duplicate records. This may occur when multiselect product attribute matches
     * several allowed values from condition simultaneously
     */
    $relatedProducts->distinct(true);

    return $relatedProducts;
}

and used it in template

<?php if ( $exist = ( $block->getProductCollection() && $block->getProductCollection()->getSize() ) ): ?>
    <?php
    $type = 'widget-product-grid';

    $mode = 'grid';

    $image = 'new_products_content_widget_grid';
    $items = $block->getProductCollection()->getItems();

    $showWishlist = true;
    $showCompare  = true;
    $showCart     = true;
    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::DEFAULT_VIEW;
    $description  = false;

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $_helper      = $this->helper( 'Magento\Catalog\Helper\Output' );
    $_imagehelper = $this->helper( 'Magento\Catalog\Helper\Image' );
    ?>

    <div class="block widget block-products-list <?= /* @noEscape */
    $mode ?>">
        <?php if ( $block->getTitle() ): ?>
            <div class="block-title">
                <strong><?= $block->escapeHtml( __( $block->getTitle() ) ) ?></strong>
            </div>
        <?php endif ?>
        <div class="block-content">
            <?= /* @noEscape */
            '<!-- ' . $image . '-->' ?>
            <div class="home-products-<?= /* @noEscape */
            $mode ?> <?= /* @noEscape */
            $mode ?>">
                <ol class="home-product-items <?= /* @noEscape */
                $type ?>">
                    <?php $iterator = 1; ?>
                    <?php foreach ( $items as $_item ): ?>
                        <?php
                        $_product = $objectManager->get( 'Magento\Catalog\Model\Product' )->load( $_item->getId() );
                        $all_data = $_product->getData();

                        $imageUrl = $_imagehelper->init( $_item, 'product_thumbnail_image' )->resize(300, 300)->getUrl();
                        ?>

                        <?= /* @noEscape */
                    ( $iterator ++ == 1 ) ? '<li class="product-item">' : '</li><li class="product-item">' ?>

                        <div class="ProductListItem">
                            <a href="<?= $block->escapeUrl($block->getProductUrl($_item)) ?>" class="ProductListItem__imageWrap">
                                <img src="<?= $imageUrl ?>"
                                     class="ProductListItem__productImage">
                            </a>
                            <div class="ProductListItem__summaryWrap">
<!--                                <div class="ProductListItem__productSize">--><?//= isset($all_data['tile_length_mm'])?$all_data['tile_length_mm']:'' . ' * ' . isset($all_data['tile_width_mm'])?$all_data['tile_width_mm']:'' ?><!--</div>-->
                                <a href="<?= $block->escapeUrl($block->getProductUrl($_item)) ?>" class="ProductListItem__productTitle">title<?= $block->escapeHtml( $_item->getName() ) ?></a>
                            </div>
                            <div class="ProductListItem__addToCartWrap">
                                <div class="ProductListItem__price">
                                    <?= $block->getProductPriceHtml( $_item, $type ) ?>/M2
                                </div>
                                <div class="ProductListItem__addToCartIcon">
                                    <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow() && $showWishlist): ?>
                                        <a href="#"
                                           data-post='<?= /* @noEscape */ $block->getAddToWishlistParams($_item) ?>' class="action towishlist" data-action="add-to-wishlist" title="<?= $block->escapeHtmlAttr(__('Add to Wish List')) ?>">
                                            <span><?= $block->escapeHtml(__('Add to Wish List')) ?></span>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?= ( $iterator == count( $items ) + 1 ) ? '</li>' : '' ?>
                    <?php endforeach ?>
                </ol>
            </div>
            <?= $block->getPagerHtml() ?>
        </div>
    </div>
<?php endif; ?>

But $block->escapeHtml( $_item->getName() ) out put null

2

3 Answers 3

0

Use this below code in your block :

protected $_productFactory;
protected $_registry;

public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    \Magento\Framework\Registry $registry,
    array $data = []
)
{
    $this->_productFactory = $productFactory;
    $this->_registry = $registry;
    parent::__construct($context, $data);
}

public function createCollection()
{
    $product = $this->_productFactory->create()->load($productId);
    //$product = $this->_registry->registry('current_product'); // For current product
    $relatedProducts = $product->getRelatedProducts();

    return $relatedProducts;
}

And use this below code in your phtml :

if (!empty($block->createCollection())) {
    echo 'Related Products <br />';
    $productFactory = $this->_productFactory->create();
    foreach ($block->createCollection() as $relatedProduct) {
        $_product = $productFactory->load($relatedProduct->getId());
        echo $relatedProduct->getId().'-->'.$_product->getPrice().'-->'.$_product->getName().'-->'.$relatedProduct->getId(); //get name
        echo "<br>";
    }
}
0
/**
 * Prepare and return product collection
 *
 * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
 */
public function createCollection()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('AntonStudio\StockUpdate\Block\RelatedProducts');

    $currentProduct = $myBlock->getCurrentProduct();
    $relatedProducts = $currentProduct->getRelatedProducts();
    /**
     * Prevent retrieval of duplicate records. This may occur when multiselect product attribute matches
     * several allowed values from condition simultaneously
     */
    $relatedProducts->distinct(true);

    return $relatedProducts;
}
0

You can create the model file for this

<?php
namespace Companyname\Vendorname\Model;

use Psr\Log\LoggerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;

class RelatedProductList
{
    protected $productRepositoryInterface;
    protected $logger;

    public function __construct(
        ProductRepositoryInterface $productRepositoryInterface,
        LoggerInterface $logger
    ) {
        $this->logger = $logger;
        $this->productRepositoryInterface = $productRepositoryInterface;
    }
    public function getRelatedProductsList()
    {
        $productId = 1;
        $relatedProductIdArray = [];
        try {
            $product = $this->productRepositoryInterface->getById($productId);
            $related = $product->getRelatedProducts();

            if (count($related)) {
                foreach ($related as $item) {
                    $relatedProductIdArray[] = $item->getId();
                }
            }
        } catch (\Exception $exception) {
            $this->logger->error($exception->getMessage());
        }

        return $relatedProductIdArray;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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