Magento 2 – Get and Check Data Attribute Value per Product

attributesmagento-2.1magento2magento2.2PHP

I create one custom date attribute for my products in backend:

enter image description here

I need to get the attribute value in the products list page and to check if the product have any data added for the product.

I try something like this but is not work well:

$expectedInDate = $_product->getResource()->getAttribute('expecdate')->getFrontend()->getValue($_product);
if(isset($expectedInDate)) : 
...........
endif; 

What is the correct way to get data attribute value and to check if has data setup per current product?

The entire code:

<?php $timezoneInterface = $objectManager->create('\Magento\Framework\Stdlib\DateTime\TimezoneInterface');  ?>
<?php $expectedInDate = $_product->getResource()->getAttribute('expecdate')->getFrontend()->getValue($_product); ?>
<?php if ($StockState->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId()) > 0 ): ?>
    <div class="stock available"><span><?= /* @escapeNotVerified */ __('In stock') ?></span></div>
<?php else: ?>
    <?php if($expectedInDate) : ?>
        <?php $date =   $timezoneInterface->date($expectedInDate)->format('m/d/Y');?>
        <div class="stock available-in"><span><?= /* @escapeNotVerified */ __('Available in:') ?><?php echo $date; ?></span></div>
    <?php else: ?>
        <div class="stock unavailable"><span><?= /* @escapeNotVerified */ __('Out of stock') ?></span></div>
    <?php endif; ?>
<?php endif; ?>

Best Answer

$value = $product->getData('expecdate'));
if ($value) {
    //print value here
}

Now depending on the attribute type you can display it in different ways.
if it's a text or textarea or int or decimal you can just echo it.
If it's dropdown attribute or multiselect you can display it like this

echo $_product->getResource()->getAttribute('expecdate')->getFrontend()->getValue($_product);

if it's a date attribute you may need to format it:

if you are inside a template you can simply do

echo $block->formatData($value);  

or

echo $block->formatDate($value, \IntlDateFormatter::LONG); //or MEDIUM, SHORT, FULL

if you don't want the time also printed and not just the date, pass the third parameter to the formatDate method true.

Related Topic