I create one custom date attribute for my products in backend:
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
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
if it's a date attribute you may need to format it:
if you are inside a template you can simply do
or
if you don't want the time also printed and not just the date, pass the third parameter to the
formatDate
methodtrue
.