Magento 2:获取自定义属性会返回“未捕获的错误:在null上调用成员函数getResource”

问题描述

我正在尝试在商品详细信息页面上的商品价格旁边显示自定义属性的值。该属性的名称为“ measurement_unit”,是Magento 2管理员中的下拉菜单。 我尝试了几种方法调用属性,但是没有任何效果。现在我收到此错误:

'[09-Sep-2020 11:52:31 UTC] PHP致命错误:未捕获错误:在public_html / vendor / magento / module-catalog / view / base / templates中以空值调用成员函数getResource() /product/price/final_price.phtml:50'

按如下方式获取属性:

<?php
$_product = $block->getProduct();
$attvalue = $_product->getResource()->getAttribute('measurement_unit')->getFrontend()->getValue($_product);
echo $attvalue;exit;
?>

整个文件如下:

final_price.html
<?php
/**
 * Copyright © Magento,Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
?>

<?php
/** @var \Magento\Catalog\Pricing\Render\FinalPriceBox $block */

/** ex: \Magento\Catalog\Pricing\Price\RegularPrice */
/** @var \Magento\Framework\Pricing\Price\PriceInterface $priceModel */
$priceModel = $block->getPriceType('regular_price');

/** ex: \Magento\Catalog\Pricing\Price\FinalPrice */
/** @var \Magento\Framework\Pricing\Price\PriceInterface $finalPriceModel */
$finalPriceModel = $block->getPriceType('final_price');
$idSuffix = $block->getIdSuffix() ? $block->getIdSuffix() : '';
$schema = ($block->getZone() == 'item_view') ? true : false;
?>
<?php if ($block->hasSpecialPrice()) :?>
    <span class="special-price">
        <?= /* @noEscape */ $block->renderAmount($finalPriceModel->getAmount(),[
            'display_label'     => __('Special Price'),'price_id'          => $block->getPriceId('product-price-' . $idSuffix),'price_type'        => 'finalPrice','include_container' => true,'schema' => $schema
        ]); ?>
    </span>
    <span class="old-price">
        <?= /* @noEscape */ $block->renderAmount($priceModel->getAmount(),[
            'display_label'     => __('Regular Price'),'price_id'          => $block->getPriceId('old-price-' . $idSuffix),'price_type'        => 'oldPrice','skip_adjustments'  => true
        ]); ?>
    </span>
<?php else :?>
    <?= /* @noEscape */ $block->renderAmount($finalPriceModel->getAmount(),[
        'price_id'          => $block->getPriceId('product-price-' . $idSuffix),'schema' => $schema
    ]);?>

<?php
$_product = $block->getProduct();
$attvalue = $_product->getResource()->getAttribute('measurement_unit')->getFrontend()->getValue($_product);
echo $attvalue;exit;
?>

<?php endif; ?>



<?php if ($block->showMinimalPrice()) :?>
    <?php if ($block->getUseLinkForAsLowAs()) :?>
        <a href="<?= $block->escapeUrl($block->getSaleableItem()->getProductUrl()) ?>" class="minimal-price-link">
            <?= /* @noEscape */ $block->renderAmountMinimal() ?>
        </a>
    <?php else :?>
        <span class="minimal-price-link">
            <?= /* @noEscape */ $block->renderAmountMinimal() ?>
        </span>
    <?php endif?>
<?php endif; ?>

我想问问是否有人可以提供有关如何正确获取属性的建议?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)