:::: MENU ::::
Posts tagged with: product attribute

Magento 2 Create Yes No Attribute Programmatically

This tutorial is about Create Yes No Attribute Programmatically in Magento 2. Obviously, there are many ways and techniques of doing a task but if you are looking for a better and dynamic way then this tutorial may satisfy your needs. Creating Yes No attributes programmatically in Magento 2 is explained below. Let’s have a look at how we can do this.

Here I am creating the upgradeData script that will add custom product attribute with yes and no options.

<?php
 namespace QaisarSatti\HelloWorld\Setup;

 use Magento\Eav\Setup\EavSetup;
 use Magento\Eav\Setup\EavSetupFactory;
 use Magento\Framework\Setup\UpgradeDataInterface;
 use Magento\Framework\Setup\ModuleContextInterface;
 use Magento\Framework\Setup\ModuleDataSetupInterface;

class upgradeData implements UpgradeDataInterface {
 private $eavSetupFactory;
 protected $logger;

public function __construct(EavSetupFactory $eavSetupFactory,\Psr\Log\LoggerInterface $logger) {
 $this->eavSetupFactory = $eavSetupFactory;
 $this->logger = $logger;
 }

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
 
 
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
 $eavSetup->addAttribute(
 \Magento\Catalog\Model\Product::ENTITY,
 'subscripion_product',[
 'type' => 'text',
 'backend' => '',
 'frontend' => '',
 'label' => 'Enable Subscription',
 'input' => 'select',
 'class' => '',
 'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
 'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
 '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' => ''
 ]
 );
 
 
 }
 
 }

That’s it from this tutorial. I strongly believe there is always room for improvement. So I am open to any suggestion and feedback. Please feel free to leave hat you are thinking in the comments section below. Cheers.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 4, 2019


Magento 2 add column in quote table and order table

This tutorial is about Magento 2 add column in quote table and order table .i.e how to get order and quote column value in Magento 2. And in this tutorial, I will try to explain it briefly and in a simple way.

If you have created a custom column for orders. I found a question and I would use it as a reference here and will share the piece of code as well.

<?php

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class UpgradeSchema implements UpgradeSchemaInterface
{
   
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();

        $quote = 'quote';
        $orderTable = 'sales_order';

        $setup->getConnection()
            ->addColumn(
                $setup->getTable($quote),
                'mediabasebestellnummer',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'comment' =>'MediabaseNummer'
                ]
            );
        //Order table
        $setup->getConnection()
            ->addColumn(
                $setup->getTable($orderTable),
                'mediabasebestellnummer',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'comment' =>'MediabaseNummer'
                ]
            );

        $setup->endSetup();
    }
}

And now you want to get the custom attribute when you have an order. how to do it?. Let us have a look at the ways to achieve it. If you are using the following method

$custom = $order->getCustomAttribute('mediabasebestellnummer');

It may not work properly. There are a couple of ways to do it. We will have a brief look at this tutorial.

First of all, check if the column is created in the sales_order table

Now we can get the values by

$order->getMediabasebestellnummer();

Or

$order->getData('mediabasebestellnummer');

For adding the data

$order->setMediabasebestellnummer('test value')->save();

OR

$order->setData('mediabasebestellnummer','test value')->save();

Or

$data = array('mediabasebestellnummer'=>'test');
$order->setData($data)->save();

I have tried to explain it in a simple way as there are many ways to perform this task.

Furthermore, make sure you have file fieldset.xml in your module to convert data from quote to order.

Following code will do the job for us.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
    <scope id="global">
        <fieldset id="sales_convert_quote">
            <field name="mediabasebestellnummer">
                <aspect name="to_order" />
            </field>
        </fieldset>
    </scope>
</config>

Also, it is used when you have column in both quote tableand order table.

That’s it from this tutorial. I hope it serves the purpose. Since these are learning tutorials, please feel free to drop any suggestions or queries in the comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 4, 2019


Magento 2 product count by attribute

Today we talk about how in Magento 2 product count by attribute. This tutorial included get product count by product attribute values. Following this example you can get count product by any attribute. For using this example you just need to replace you_attribute_code with you attribute code i.e color. So let start with our example.

    protected $_productCollectionFactory;
    protected $attributFactory;
    protected $eavConfig;

    public function __construct(
   
        \Magento\Catalog\Model\ResourceModel\Product $productFactory,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\CollectionFactory $attributFactory,
        \Magento\Eav\Model\Config $eavConfig,

       
    ) {
   
        $this->eavConfig = $eavConfig;
        $this->attributFactory = $attributFactory;
        $this->_productCollectionFactory = $productFactory;            

    }


    public function getProductCountByAttributeCode()
     {
        $attributeCode = ‘you_attribute_code’;
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        $attributFactory = $this->attributFactory->create()->setStoreFilter(0, false);
         $itemCollection = $this->_productCollectionFactory;
        $attributFactory->getSelect()
        ->joinLeft(
            array('value_table' => $itemCollection->getTable('catalog_product_entity_int')),
            'main_table.option_id=value_table.value AND main_table.attribute_id=value_table.attribute_id', 'entity_id')
        ->reset(\Zend_Db_Select::COLUMNS)
        ->columns(array('main_table.option_id',new \Zend_Db_Expr('COUNT(value_table.entity_id)')))
        ->where('main_table.attribute_id=:attribute_id')
        ->group('main_table.option_id');
        $result = $itemCollection->getConnection()->fetchPairs(
        $attributFactory->getSelect(), array('attribute_id' => $attribute->getId()));
        return $result;        
    }

Note: Using above example you can count product by any attribute.

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 get product attribute by attribute groups

Today we talk about how in Magento 2 get product attribute by attribute groups. Sometime custom requirement need to show the product attributes by its own groups. So we learn how to get product attribute by their attribute groups. So let’s start it.
Create a block with following injecting class

\Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory

<?php
namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{

  protected $_productloader;
  protected $request;
  protected $_groupCollection;


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Group\CollectionFactory $_groupCollection,
        \Magento\Framework\App\Request\Http $request

    ) {


        $this->_productloader = $_productloader;
        $this->request = $request;
        $this->_groupCollection = $_groupCollection;
        parent::__construct($context);
    }
//get the product
    public function getLoadProduct()
    {
          $id=10;
     
        return $this->_productloader->create()->load($id);
    }
//Get attribute group id
    public function getAttributeGroupId($attributeSetId)
    {
         $groupCollection = $this->_groupCollection->create();
         $groupCollection->addFieldToFilter('attribute_set_id',$attributeSetId);
         $groupCollection->addFieldToFilter('attribute_group_name','Grid Attributes');
         
         
         return $groupCollection->getFirstItem();

    }
    //Get all attribute groups
    public function getAttributeGroups($attributeSetId)
    {
         $groupCollection = $this->_groupCollection->create();
         $groupCollection->addFieldToFilter('attribute_set_id',$attributeSetId);
         
         $groupCollection->setOrder('sort_order','ASC');
         return $groupCollection;

    }
//get attribute by groups
 public function getGroupAttributes($pro,$groupId, $productAttributes){
        $data=[];
        $no =__('No');
        foreach ($productAttributes as $attribute){
   
          if ($attribute->isInGroup($pro->getAttributeSetId(), $groupId) && $attribute->getIsVisibleOnFront() ){
              if($attribute->getFrontend()->getValue($pro) && $attribute->getFrontend()->getValue($pro)!='' && $attribute->getFrontend()->getValue($pro)!=$no){
                $data[]=$attribute;
              }
          }

        }
 
  return $data;
 }
 
 }

Now we use the block code in our phtml file.

$_product=$block->getLoadProduct();
$groupid=$block->getAttributeGroupId($_product->getAttributeSetId());
$attributesgroups=$block->getAttributeGroups($_product->getAttributeSetId());

$productAttributes=$_product->getAttributes();




?>
 
<?php
foreach ($attributesgroups as $attributesgroup):


 $attributes=$block->getGroupAttributes($product,$attributesgroup->getAttributeGroupId(),$productAttributes);
 

 
 
 if($attributes){ ?>

 

   
            <h3 class="col label" scope="row"><?php echo $attributesgroup->getAttributeGroupName() ?></h3>
           
           
            <div class="additional-attributes-wrapper table-wrapper block">
        <table class="data table additional-attributes" id="product-attribute-specs-table">
            <tbody>
           
    <?php
    foreach ($attributes as $attribute): ?>
       
       
       
             <tr>
                    <td class="col label" scope="row"><?php echo $attribute->getFrontendLabel() ?></td>
                    <td class="col data feature" data-th="<?php echo $attribute->getFrontendLabel() ?>"><?php /* @escapeNotVerified */ echo $attribute->getFrontend()->getValue($product) ?></td>
                </tr>
           
           
       
        <?php    
    endforeach; ?>
           </tbody>
        </table>
        </div>
 <?php }
endforeach;

?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018