0

I'm facing a coding problem using Magento. I want to display the detail of a product in a recently bought template from TemplateMonster. I have created two numerical custom attributes in my product table in the database (namely PP and PR). The scope of the attributes is global in admin panel. I just can't display those two attributes on my page. I'm using the following code, above the price display:

<?php /* @escapeNotVerified */ echo $_item->getAttributeText("pp") ?>
<?php /* @escapeNotVerified */ echo $_item->getAttributeText("pr") ?>

The attributes don't appear anywhere. I don't know what am I doing wrong?

  • Hi @Nuno you got the answer ? – Manish Goswami May 15 '18 at 4:57
  • is that in magento1 or magento2 ? – hweb87 May 16 '18 at 9:24
  • It is Magento 2 but with an awful new template from template monster. I just can't figure out how they code it. – Nuno Sousa May 16 '18 at 10:06
2

Use this code

echo $_item->getResource()->getAttribute('Your_Attribute_Code')->getFrontend()->getValue($_item);
0

Please try this code:

<?php /* @escapeNotVerified */ echo $_item->getResource()->getAttribute('pp')->getFrontend()->getValue($_item); ?>
<?php /* @escapeNotVerified */ echo $_item->getResource()->getAttribute('pr')->getFrontend()->getValue($_item); ?>
  • I tried so and doesn't seem to work, I don't know why. It seems that the page encapsulates the data in some way I can't access the state of the attributes. Nothing appear in my result page – Nuno Sousa May 14 '18 at 19:16
  • Check your collection, I mean all attributes added for addAttributeToSelect with * for few fields only. – kunj May 15 '18 at 4:30
  • I'm new with Magento. How can I do that in practice? – Nuno Sousa May 15 '18 at 14:42
  • can you share your PHTML file content? – kunj May 15 '18 at 16:49
0

My products-list.phtml code is as following:

    <?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>
<?php
/**
 * Template for displaying new products widget
 *
 * @var $block \Magento\Catalog\Block\Product\Widget\NewWidget
 */
if ($exist = ($block->getProductCollection() && $block->getProductCollection()->getItems())) {
    $type = 'widget-new-list';

    $mode = 'list';
    $widgetType = $block->getProductTypes();

    $image = 'new_products_content_widget_list';
    $title = $block->getTitle();
    $items = $block->getProductCollection()->getItems();
    $label = $block->getWidgetLabel();
    $isCarousel = $block->getShowCarousel();
    $visibleCarousel = $block->getNumberToDisplay();
    $productItemWidth = $block->getItemWidth();
    $productPp = $block->getPp();
    $productPr = $block->getPr();


    $showReviews = [
        'new_product'         => false,
        'sale_product'        => false,
        'viewed_product'      => false,
        'bestsellers_product' => false,
        'rated_product'       => true,
        'manual_product'      => false
    ];

    $showWishlist = true;
    $showCompare = true;
    $showCart = true;
    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    $description = true;
}
?>

<?php ?>

<?php if ($exist):?>
    <div class="block widget featured <?php /* @escapeNotVerified */ echo $mode; ?> <?php /* @escapeNotVerified */ echo $widgetType; ?> one-product-carousel">
        <div class="block-title">
            <strong role="heading" aria-level="2"><?php /* @escapeNotVerified */ echo __($title); ?></strong>
        </div>
        <div class="block-content<?php echo $productItemWidth ? ' custom-columns' : '' ?>">

            <div class="products-<?php /* @escapeNotVerified */ echo $mode; ?> <?php /* @escapeNotVerified */ echo $mode; ?>">
                <div class="product-items <?php /* @escapeNotVerified */ echo $type; ?> <?php if ($isCarousel): ?>owl-carousel<?php endif; ?>"
                    <?php if ($isCarousel): ?>
                        data-mage-init='{"carousel": {"items": "<?php /* @escapeNotVerified */ echo $visibleCarousel; ?>"}}'
                    <?php endif; ?>>
                    <?php $iterator = 1; ?>
                    <?php foreach ($items as $_item): ?>
                        <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<div class="product-item"' . ' ' . $productItemWidth . '>'
                            : '</div><div class="product-item"' . ' ' . $productItemWidth . '>' ?>
                    <div class="container">
                        <?php /* @escapeNotVerified */ echo ($block->getShowLabel()) ? '<span class="product-label">' . $label . '</span>' : ''; ?>
                        <div class="product-item-info">

                            <div class="product-item-details">
                                <div class="opw-left-side">
                                    <strong class="product-item-name">
                                        <a title="<?php echo $block->escapeHtml($_item->getName()) ?>"
                                           href="<?php /* @escapeNotVerified */ echo $block->getProductUrl($_item) ?>"
                                           class="product-item-link">
                                            <?php echo $block->escapeHtml($_item->getName()) ?>
                                        </a>
                                    </strong>

                                    <?php if ($description):?>
                                        <div class="product description product-item-description">
                                            <?php /* @escapeNotVerified */ echo $_item->getShortDescription(); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>


                                <div class="opw-right-side">
                                    <?php echo /* @escapeNotVerified */ $block->getProductPriceHtml($_item, $type); ?>
                                    <!--div class="points-box"-->


                                    <?php /* @escapeNotVerified */ echo $_item->getResource()->getAttribute('pp')->getFrontend()->getValue($_item); ?>
                                    <?php /* @escapeNotVerified */ echo $_item->getResource()->getAttribute('pr')->getFrontend()->getValue($_item); ?>

                                      <!--'<div  class="points-box"> PP ' . $_item->getResource()->getAttribute('pp') .
                                      : '</div><div class="points-box" > PR ' . $_item->getResource()->getAttribute('pr') . '</div>' ?-->

                                      <?php if ($templateType): ?>
                                        <?php echo $block->getReviewsSummaryHtml($_item, $templateType, $showReviews[$widgetType]) ?>
                                    <?php endif; ?>
                                    <?php if ($showWishlist || $showCompare || $showCart): ?>
                                        <div class="product-item-actions">
                                            <?php if ($showCart): ?>
                                                <div class="actions-primary">
                                                    <?php if ($_item->isSaleable()): ?>
                                                        <?php if ($_item->getTypeInstance()->hasRequiredOptions($_item)): ?>
                                                            <button class="action tocart primary"
                                                                    data-mage-init='{"redirectUrl":{"url":"<?php /* @escapeNotVerified */ echo $block->getAddToCartUrl($_item) ?>"}}'
                                                                    type="button" title="<?php /* @escapeNotVerified */ echo __('Add to Cart') ?>">
                                                                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                                            </button>
                                                        <?php else: ?>
                                                            <?php
                                                            $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
                                                            $postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()])
                                                            ?>
                                                            <button class="action tocart primary"
                                                                    data-post='<?php /* @escapeNotVerified */ echo $postData; ?>'
                                                                    type="button" title="<?php /* @escapeNotVerified */ echo __('Add to Cart') ?>">
                                                                <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                                            </button>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <?php if ($_item->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>
                                            <?php endif; ?>
                                            <?php if ($showWishlist || $showCompare): ?>
                                                <div class="actions-secondary" data-role="add-to-links">
                                                    <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow() && $showWishlist): ?>
                                                        <a href="#"
                                                           data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_item); ?>'
                                                           class="action towishlist" data-action="add-to-wishlist"
                                                           title="<?php /* @escapeNotVerified */ echo __('Add to Wish List') ?>">
                                                            <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                                                        </a>
                                                    <?php endif; ?>
                                                    <?php if ($block->getAddToCompareUrl() && $showCompare): ?>
                                                        <?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');?>
                                                        <a href="#" class="action tocompare"
                                                           data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_item);?>'
                                                           title="<?php /* @escapeNotVerified */ echo __('Add to Compare') ?>">
                                                            <span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
                                                        </a>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>



                            </div>
                            <a href="<?php /* @escapeNotVerified */ echo $block->getProductUrl($_item) ?>" class="product-item-photo">
                                <?php echo $block->getImage($_item, $image)->toHtml(); ?>
                            </a>
                        </div>
                    </div>
                        <?php echo($iterator == count($items)+1) ? '</div>' : '' ?>
                    <?php endforeach ?>
                </div>
            </div>
            <?php echo $block->getPagerHtml() ?>

        </div>
    </div>
<?php endif;?>
  • Somehow the page encapsulates its attributes in their own objects and I just can't decrypt the code. – Nuno Sousa May 16 '18 at 9:54
0

I tried to configure the 'getters' in Product page (Product.php) in order to access the value of the attributes. Unsuccessfully.

<?php

/**
 *
 * Copyright © 2015 TemplateMonster. All rights reserved.
 * See COPYING.txt for license details.
 *
 */

namespace TemplateMonster\FeaturedProduct\Block\FeaturedProduct\Widget;

use Magento\Customer\Model\Context as CustomerContext;

class Product extends \Magento\Catalog\Block\Product\AbstractProduct implements \Magento\Widget\Block\BlockInterface
{

    /**
     * Default cache time
     */
    const CACHE_TIME = 86400;

    protected $_template = 'TemplateMonster_FeaturedProduct::widget/products.phtml';
    protected $_productFactory;
    protected $_imageBuilder;
    protected $_httpContext;


    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \TemplateMonster\FeaturedProduct\Model\ProductFactory $productFactory,
        \Magento\Framework\App\Http\Context $httpContext,
        array $data = [])
    {
        $this->_imageBuilder = $context->getImageBuilder();
        $this->_productFactory = $productFactory;
        $this->_httpContext = $httpContext;
        parent::__construct($context, $data);
    }


    public function _construct()
    {
        $this->addData(
            ['cache_lifetime' => self::CACHE_TIME, 'cache_tags' => [\Magento\Catalog\Model\Product::CACHE_TAG]]
        );
        parent::_construct();
    }

    /**
     * Get Key pieces for caching block content
     *
     * @return array
     */
    public function getCacheKeyInfo()
    {
        $cacheKeyFromData = "TM_";
        $configData = $this->getData();

        foreach($configData as $value) {
            if(is_string($value)) {
                $cacheKeyFromData .= $value;

            }
        }
        return [
            $cacheKeyFromData,
            $this->_storeManager->getStore()->getId(),
            $this->_design->getDesignTheme()->getId(),
            $this->_httpContext->getValue(CustomerContext::CONTEXT_GROUP),
            'template' => $this->getTemplate()
        ];
    }

    public function getCacheLifetime()
    {
        if(!$this->getData('cache_lifetime')) {
            return self::CACHE_TIME;
        }
        return $this->getData('cache_lifetime');
    }

    public function getProductIds()
    {
        $productArr = [];
        $productIdsStr = $this->getData('product_ids');
        if($productIdsStr && is_string($productIdsStr)) {
            $productArr = explode(',',$productIdsStr);
        }
        return $productArr;
    }

    public function getItemWidth()
    {
        $productItemWidth = '';
        $productPerRow = $this->getNumberPerRow();
        if ($productPerRow) {
            if (!$this->getShowCarousel()) {
                $productItemWidth = 'style="width: ' . 100 / $productPerRow . '%;"';
            }
        }
        return $productItemWidth;
    }

    public function getPp()
    {
        $productPp = $this->getData('pp');
        return 'PP ' . $productPp;
    }

   public function getPr()
    {
        $productPp = $this->getData('pr');
        return 'PR ' . $productPp;
    }

    /**
     * Return Product Collection
     * @return bool
     */
    protected function _getProductCollection()
    {
        $productIds = $this->getProductIds();
        $numberPerView = (int)$this->getNumberPerView();
        $productType = $this->getProductTypes();
        try {
            $productFactory = $this->_productFactory->create($productType);
        } catch(\Exception $e) {
            return false;
        }
        $productCollection = $productFactory->getPreparedCollection($numberPerView,$productIds);
        return $productCollection;
    }

    /**
     * Return HTML block with price
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param string $priceType
     * @param string $renderZone
     * @param array $arguments
     * @return string
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function getProductPriceHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null,
        $renderZone = \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST,
        array $arguments = []
    ) {
        if (!isset($arguments['zone'])) {
            $arguments['zone'] = $renderZone;
        }
        $arguments['zone'] = isset($arguments['zone'])
            ? $arguments['zone']
            : $renderZone;
        $arguments['price_id'] = isset($arguments['price_id'])
            ? $arguments['price_id']
            : 'old-price-' . $product->getId() . '-' . $priceType;
        $arguments['include_container'] = isset($arguments['include_container'])
            ? $arguments['include_container']
            : true;
        $arguments['display_minimal_price'] = isset($arguments['display_minimal_price'])
            ? $arguments['display_minimal_price']
            : true;

        /** @var \Magento\Framework\Pricing\Render $priceRender */
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');

        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product,
                $arguments
            );
        }
        return $price;
    }

/**
     * Return HTML block with price
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param string $priceType
     * @param string $renderZone
     * @param array $arguments
     * @return string
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function getProductPriceHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null,
        $renderZone = \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST,
        array $arguments = []
    ) {
        if (!isset($arguments['zone'])) {
            $arguments['zone'] = $renderZone;
        }
        $arguments['zone'] = isset($arguments['zone'])
            ? $arguments['zone']
            : $renderZone;
        $arguments['price_id'] = isset($arguments['price_id'])
            ? $arguments['price_id']
            : 'old-price-' . $product->getId() . '-' . $priceType;
        $arguments['include_container'] = isset($arguments['include_container'])
            ? $arguments['include_container']
            : true;
        $arguments['display_minimal_price'] = isset($arguments['display_minimal_price'])
            ? $arguments['display_minimal_price']
            : true;

        /** @var \Magento\Framework\Pricing\Render $priceRender */
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');

        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product,
                $arguments
            );
        }
        return $price;
    }

    /**
     * Prepare collection with new products
     *
     * @return \Magento\Framework\View\Element\AbstractBlock
     */
    protected function _beforeToHtml()
    {
        $this->setProductCollection($this->_getProductCollection());
        return parent::_beforeToHtml();
    }

}

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.