3

I am creating a custom product attribute in Magento 2 by custom module InstallData.php code following

    <?php
namespace Awa\Brand\\Setup;

use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    /**
     * EAV setup factory
     *
     * @var \Magento\Eav\Setup\EavSetupFactory
     */
    private $eavSetupFactory;

    /**
     * Constructor
     *
     * @param EavSetupFactory $eavSetupFactory
     */
    public function __construct(
        EavSetupFactory $eavSetupFactory
    ) {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $setup->startSetup();

        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);


        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'awa_brand',
            [
                'type' => 'int', 
                'backend' => '',
                'frontend' => '',
                'label' => 'Attribute Select',
                'input' => 'select', 
                'class' => '',
                'source' => 'Awa\Brand\Model\Config\Source\Options',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'visible' => true,
                'required' => true,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => false,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to' => ''
            ]
        );

        $setup->endSetup();
    }
}

and source Module is bellow

    <?php 
namespace Awa\Brand\Model\Config\Source;

class Options extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * to option array
     *
     * @return array
     */
     public function getAllOptions()
    {
        $_objManager = \Magento\Framework\App\ObjectManager::getInstance();
        $brandData = $_objManager->create('Awa\Brand\Model\Brand')->getCollection();
        $options = array();
        $options[] =[
                'value' => '',
                'label' => __('-- Please Select --')
            ];
        foreach($brandData as $_brand){
            $options[] =  [
                'value' => $_brand->getBrandId(),
                'label' => __($_brand->getTitle())
            ];
        }
        return $options;

    }

    public function toOptionArray()
    {
        $_objManager = \Magento\Framework\App\ObjectManager::getInstance();
        $brandData = $_objManager->create('Awa\Brand\Model\Brand')->getCollection();
        $options = array();
        $options[] =[
                'value' => '',
                'label' => __('-- Please Select --')
            ];
        foreach($brandData as $_brand){
            $options[] =  [
                'value' => $_brand->getBrandId(),
                'label' => __($_brand->getTitle())
            ];
        }
        return $options;

    }
}

This attribute created successfull

When I try to get product collection by this attribute its not working and this attribute not showing product collection

MY get product collection code following

<?php
$_product = $block->getProduct();

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->get('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()
->addAttributeToFilter('awa_brand',array('eq' => $_product->getAwaBrand()))
->setPageSize(3);

foreach($collection as $product):
    echo '<pre/>'; print_r($product->getData());exit;
endforeach;

?>

2 Answers 2

3

Before addAttributeToFilter Function You Must Select All Attribute Using addAttributeToSelect Function

$collection = $productCollection->create()
->addAttributeToSelect('*')
->addAttributeToFilter('awa_brand',array('eq' => $_product->getAwaBrand()))
->setPageSize(3);
3
  • i already try this way but not work Mar 6, 2019 at 12:44
  • hi Ronak Rathod before you try ! create a product attribute programmatically and set custom 'source' and then try to get product collection ! why attribute is show in product collection ? Mar 6, 2019 at 12:51
  • source is define for get the Options not for actually attribute data for product Mar 7, 2019 at 20:18
1

Use of objectmanager directly is not a good practice.
See the below code may help you:

protected $_productloader;

public function __construct(
     \Magento\Catalog\Model\ProductFactory $productloader
)
{
     $this->_productloader     = $productloader;
}

// function in which you want to access

function abc()
{
     $productId      = 10;
     $_product       = $this->_productloader->create()->load($productId);
     $awa_brand      = $_product->getData('awa_brand');
}

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.