:::: MENU ::::

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


Get base url current url in Magento 2

This tutorial is about Get base URL,current URL in Magento 2 .i.e how to get base URL current URL in Magento 2. you can also get media url and any custom url following this example. And in this tutorial, I will try to explain it briefly and in a simple way. I will share the code snippet below.

Get base url and current url in Magento 2

First lets note down the steps.

Step 1: Declare in (your module name)_HelloWorld
Step 2: Get current URL and base URL in the template (.phtml) file

Moving forward let us explain these steps step by step.

Declare in (your module name)_HelloWorld

You will use a block class of the module (your module name)_HelloWorld, then possibly inject the object of StoreManagerInterface and UrlInterface in the constructor of the module’s block class. You will work with two functions in the below class: getStoreManagerData() and getUrlInterfaceData().

  • In getStoreManagerData() function, you will use object of StoreManagerInterface to get the base and current url.
  • In getUrlInterfaceData() function, you will use object of UrlInterface to get the base and current url
  • .

    Open app/code/QaisarSatti/HelloWorld/Block/HelloWorld.php class and run the code:

    <?php
    namespace QaisarSatti\HelloWorld\Block;
    class HelloWorld extends \Magento\Framework\View\Element\Template
    {
            protected $_storeManager;
            protected $_urlInterface;
     
        public function __construct(
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Framework\UrlInterface $urlInterface,    
        )
        {        
            $this->_storeManager = $storeManager;
            $this->_urlInterface = $urlInterface;
        }
       
       
       
        /**
         * Printing URLs using StoreManagerInterface
         */

        public function getStoreManagerData()
        {    
            echo $this->_storeManager->getStore()->getId() . '<br />';
           
            // by default: URL_TYPE_LINK is returned
            echo $this->_storeManager->getStore()->getBaseUrl() . '<br />';        
           
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB) . '<br />';
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK) . '<br />';
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . '<br />';
            echo $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC) . '<br />';
           
            echo $this->_storeManager->getStore()->getUrl('product/33') . '<br />';
           
            echo $this->_storeManager->getStore()->getCurrentUrl(false) . '<br />';
               
            echo $this->_storeManager->getStore()->getBaseMediaDir() . '<br />';
               
            echo $this->_storeManager->getStore()->getBaseStaticDir() . '<br />';    
        }
       
        /**
         * Printing URLs using URLInterface
         */

        public function getUrlInterfaceData()
        {
            echo $this->_urlInterface->getCurrentUrl() . '<br />';
           
            echo $this->_urlInterface->getUrl() . '<br />';
           
            echo $this->_urlInterface->getUrl('helloworld/general/enabled') . '<br />';
           
            echo $this->_urlInterface->getBaseUrl() . '<br />';
        }  
    }
    ?>

    Step 2:

    Get base URL and current URL in the template file

    Use the following piece of code:

    <?php echo $block->getUrl('hello/test'); ?>
    <?php echo $block->getBaseUrl(); ?>

    Furthermore, 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


    Get post data in observer magento 2

    This tutorial is about Get post data, in observer Magento 2 .i.e how to get post data, in Checkout success observer in Magento 2 or any save after observer action. And in this tutorial, I will try to explain it briefly and in a simple way.

    We can add the request to a class through dependency injection and access it via a singleton.

    Use the following code:

    protected $_request;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
    ) {
        $this->_request = $request;
    }

    Inside function get post data in the following way:

    $this->_request->getParams();

    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 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 Update product attribute value

    This article is about Magento 2 – Update product attribute value . Updating product attribute value can be tricky sometimes. In this tutorial i will try to explain it swiftly and in a simple way. There can be various conditions in this matter. Like if someone wants to update the attribute values one by one or as a whole. Here, we are looking t update only one attribute value.

    We can set all the values into one object (also we can use set for each attribute) & using set method we can save the product attribute with the help of productRepository or product model.

    Furthermore When we use this method, there is a chance to get delays while updating the values like it may take 40 to 50 sec approx for one product . In our case we want to update only one attribute value. To render entire collection & updating the value might will take some ms delay.
    So to update only one attribute value, we can do so by using the following code.

    Consider the example here.

    $item->setWidth(10);

    $item->save();

    We can use “updateAttributes” method to update Specific Attribute for product instead of updating all the update.

    Here we have to pass 3 parameters.

    Ex: $productIds , $attrData, $storeId
    $objectManager->get(‘Magento\Catalog\Model\Product\Action’)

    ->updateAttributes( [$item],[‘width’ => 10],  $YourStoreID );

    Similarly

    $this->action->updateAttributes([$productObj->getId()], [‘Yourattribute_code’ => ‘Yourvalue’], $StoreId);

    I am also providing the path for reference, it may vary depending upon your settings.

    Magento\Catalog\Model\Product\Action

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

    Author: Qaisar Satti
    Category: Magento 2
    Last Modified: January 11, 2019


    Magento 2 Change theme

    This tutorial is about Magento 2 Change theme .i.e how to Change theme and switch your store to default theme in magento 2. I assume your question is,is it possible? the answer is, Yes. It is possible. And in this tutorial i will try to explain it briefly and in a simple way.

    So this is quite simple i would say.There is not much of a rocket science in here. Lets see how can we do it. I will try to break it in steps so that it would remain simple and easy to learn.

    Above all The default theme in Magento 2 is called Magento Blank. To activate it, follow these steps:

    1. Login into your admin panel and navigate to Stores->Settings ->Configuration section .
    2. In the General tab press Design.
    3. Select Magento Blank among the list of available themes in Design Theme option, press the Save Config button in the top right.
    4.Refresh the Magento cache.
    5.Check how the new theme appears on the site frontend.

    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 comments section. That will definitely be highly appreciated.

    Author: Qaisar Satti
    Category: Magento
    Last Modified: January 11, 2019


    Pages:1234567...22