I'm trying to pull a product collection into a CMS page based on an attribute. I have the collection pulled in and I can return the SKU and URL of the product in my loop, but the product name returns null. Am i loading this collection in correctly? Is there a better way to go about doing this.
Here is my block:
namespace {{vendor}}\ManufacturerPages\Block;
class Manufacturer extends \Magento\Framework\View\Element\Template {
protected $categoryFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
array $data = []
){
$this->_productCollectionFactory = $productCollectionFactory;
$this->_catalogProductVisibility = $catalogProductVisibility;
parent::__construct($context, $data);
}
public function getProductCollection() {
$attrId = $this->getAttrId();
$collection = $this->_productCollectionFactory->create();
$collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
$collection->addAttributeToFilter('manufacturer', ['eq' => $attrId]);
return $collection;
}
}
This is the code in the template:
$productCollection = $this->getProductCollection();
foreach ($productCollection as $product) {
var_dump(($product->getData('name')));
var_dump(($product->getId()));
var_dump(($product->getProductUrl()));
var_dump(($product->getSku()));
}
And i'm calling in template and block in the cms page with this line:
{{block class="{{vendor}}\ManufacturerPages\Block\Manufacturer" attr_id="2337" template="{{vendor}}_ManufacturerPages::manufacturers/pages.phtml"}}
In case anyone is already thinking this, the cms page widget that will pull in a product list is no longer working on the site i'm building. I have found a github post about the issue being corrected in v2.1, but of reasons out of my control I wont be able to update the site before it goes live. So I'm trying to find a work around.
Best Answer
You need to add the
name
field to your select: