2

When I compare products on my store, there are a lot of I filled attributes and despite there being no value for each product I’m comparing, it still shows the attribute and a line of “N/A” values.

How can I fix this?

It also did show unused values with “N/A” on the product page but I edited the

attributes.phtml

file to fix this. I’m unsure on how I could edit the compare file to solve this though.

3 Answers 3

1

See hide empty attributes from compare product

However, the issue of one but not the other being set is not fixed. I couldn't find a fix that was easily accessible.

Magento 1 How to Hide Empty or Null Attribute in Compare Page

These are from Magento 1 and not Magento 2. I have not tested it but am looking for a solution as well for Magento 2.

0

use plugin for Magento\Catalog\Block\Product\Compare\ListCompare::getAttributes

frontend/etc/di.xml:

    <type name="Magento\Catalog\Block\Product\Compare\ListCompare">
        <plugin sortOrder="1" name="[NAME]" type="[VENDOR]\[MODULE]\Plugin\Block\Product\Compare\ListComparePlugin"/>
    </type>

VENDOR/MODULE/Plugin/Block/Product/Compare/ListComparePlugin.php

public function afterGetAttributes(ListCompare $subject, $result)
{
    foreach ($subject->getItems() as $item) {
        foreach (array_keys($result) as $attributeCode) {
            if (empty(trim($item->getData($attributeCode) ?? ''))) {
                unset($result[$attributeCode]);
            }
        }
    }

    return $result;
}
-1

Override Magento\Catalog\Block\Product\Compare\ListCompare using Preference

 <preference for="Magento\Catalog\Block\Product\Compare\ListCompare"
            type="Vendor\Catalog\Block\Product\Compare\ListCompare"/>

And update below function

/**
 * Retrieve Product Compare Attributes
 *
 * @return array
 */
public function getAttributes()
{
    if ($this->_attributes === null) {
        $this->_attributes = $this->getItems()->getComparableAttributes();
    }

    // Remove Null Attribute From Compare List
    foreach ($this->_attributes as $attribute) {
        $size  = sizeof($this->getItems());
        $count = 0;

        foreach ($this->getItems() as $item) {
            $itemAttribute = $item->getData($attribute->getName());
            $trimAttribute = trim($itemAttribute);
            if (is_null($itemAttribute) || empty($trimAttribute)) {
                $count++;
            }

            if ($count == $size) {
                unset($this->_attributes[$attribute->getName()]);
            }
        }
    }
    return $this->_attributes;
}

This is working for me in Magento2

Your Answer

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

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