We sacrifice by not doing any other technology, so that you get the best of Magento.

We sacrifice by not doing any other technology, so that you get the best of Magento.

    Magento 2 Install / Uninstall Sample Data via Command Line

    In this tutorial, we will talk about how to Install/Uninstall Sample Data via Command Line . As you know, Magento 2 have many commands in bin/magento folder. But it may be difficult to get approach with this, so let me explain about it in more detail.

    Install / Uninstall Sample Data via command line

    Go to Magento root folder and see usages:

    php bin/magento maintenance:enable
    

    Result:

    Usage:
      sampledata:deploy [options]
    
    Options:
          --no-update       Update composer.json without executing composer update
      -h, --help            Display this help message
      -q, --quiet           Do not output any message
      -V, --version         Display this application version
          --ansi            Force ANSI output
          --no-ansi         Disable ANSI output
      -n, --no-interaction  Do not ask any interactive question
      -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
    
    Help:
      Deploy sample data modules

    Install Sample Data Syntax

    php bin/magento sampledata:deploy [options]
    

    By default, it will update latest version of sample data via composer, then install it. You can disable it with parameter: --no-update

    php bin/magento sampledata:deploy --no-update
    

    Uninstall Sample Data Syntax

    Go to Magento root folder and see usages:

    php bin/magento sampledata:remove -h
    

    Output:

    Usage:                                                                                                                     
      sampledata:remove [options]                                                                                              
                                                                                                                               
    Options:                                                                                                                   
          --no-update       Update composer.json without executing composer update                                             
      -h, --help            Display this help message                                                                          
      -q, --quiet           Do not output any message                                                                          
      -V, --version         Display this application version                                                                   
          --ansi            Force ANSI output                                                                                  
          --no-ansi         Disable ANSI output                                                                                
      -n, --no-interaction  Do not ask any interactive question                                                                
      -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug 
                                                                                                                               
    Help:                                                                                                                      
      Remove all sample data packages from composer.json

    Syntax:

    php bin/magento sampledata:remove [options]   
    

     

    Magento 2 How to Add Admin User via Command Line

    In this tutorial, we will talk about How to Add Admin User via Command Line. As you know, from Magento 2, they add many commands in bin/magento. It may be difficult to get approach with this, so let me explain about ‘How to Add Admin User via Command Line’  in more detail .

    How to Add Admin User via Command Line

    Go to Magento root folder and see the usage:

    php bin/magento admin:user:create --help
    

    Output:

    Usage:
      admin:user:create [options]
    
    Options:
          --admin-user=ADMIN-USER                    (Required) Admin user
          --admin-password=ADMIN-PASSWORD            (Required) Admin password
          --admin-email=ADMIN-EMAIL                  (Required) Admin email
          --admin-firstname=ADMIN-FIRSTNAME          (Required) Admin first name
          --admin-lastname=ADMIN-LASTNAME            (Required) Admin last name
          --magento-init-params=MAGENTO-INIT-PARAMS  Add to any command to customize Magento initialization parameters
                                                     For example: "MAGE_MODE=developer&MAGE_DIRS[base][path]=/var/www/example.com&MAGE_DIRS[cache][path]=/var/tmp/cache"
      -h, --help                                     Display this help message
      -q, --quiet                                    Do not output any message
      -V, --version                                  Display this application version
          --ansi                                     Force ANSI output
          --no-ansi                                  Disable ANSI output
      -n, --no-interaction                           Do not ask any interactive question
      -v|vv|vvv, --verbose                           Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
    
    Help:
      Creates an administrator

    Let’s create a admin account with the following information:

    User: magemonkeys
    Password: WeLoveMagento123
    Email: hi@magemonkeys.com
    First Name: magemonkeys
    Last Name: Family
    See the command line is:

    php bin/magento admin:user:create --admin-user=magemonkeys --admin-password=WeLoveMagento123 --admin-email=hi@magemonkeys.com --admin-firstname=magemonkeys --admin-lastname=Family
    

    And thus we have successfully created a new admin account, it returned message:

    Created Magento administrator user named magemonkeys 
    

     

    Overriding controller in Magento 1.9

    Your controller rewrite XML part should look like this:

    <frontend>
        <routers>
            <contacts>
                <args>
                    <modules>
                        <Namespace_Modulename before="Mage_Contacts">Namespace_Modulename</Namespace_Modulename>
                    </modules>
                </args>
            </contacts>
        </routers>
    </frontend>

    As you can see instead of using <contactsmodule> node we are here using <contacts> node. <contacts> is the router node which is used by Mage_Contacts module.

    After this change is done, do not forget to flush the cache again.

    It is a good practice to keep dependency in your module as shown below.

    File : Namespace_Modulename.xml

    <?xml version="1.0"?>
    <config>
        <modules>
            <Namespace_Modulename>
                <active>true</active>
                <codePool>local</codePool>
                <depends>
                    <Mage_Contacts />
                </depends>
            </Namespace_Modulename>
        </modules>
    </config>

    This clearly indicates that your module has a dependency on Mage_Contacts module and thus Magento will load your module only after Mage_Contacts is loaded.

     

    Add an item to the cart with a custom price in magento

    This functionality not available by default in Magento. I have used the below solution.
    You can call this event checkout_cart_product_add_after in the observer.

    File Path app/code/local/{namespace}/{yourmodule}/etc/config.xml

    <config>
        ...
        <frontend>
            ...
            <events>
                <checkout_cart_product_add_after>
                    <observers>
                        <unique_event_name>
                            <class>{{modulename}}/observer</class>
                            <method>overridePrice</method>
                        </unique_event_name>
                    </observers>
                </checkout_cart_product_add_after>
            </events>
            ...
        </frontend>
        ...
    </config>
    

    And then create an Observer class in this file app/code/local/{namespace}/{yourmodule}/Model/Observer.php

    <?php
        class <namespace>_<modulename>_Model_Observer
        {
            public function overridePrice(Varien_Event_Observer $observer)
            {
                // Get the quote item
                $item = $observer->getQuoteItem();
                // Ensure we have the parent item, if it has one
                $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
                // Load the custom price
                $price = $this->_getPriceByItem($item);
                // Set the custom price
                $item->setCustomPrice($price);
                $item->setOriginalCustomPrice($price);
                // Enable super mode on the product.
                $item->getProduct()->setIsSuperMode(true);
            }
            
            protected function _getPriceByItem(Mage_Sales_Model_Quote_Item $item)
            {
                $price;
                
                //use $item to determine your custom price.
                
                return $price;
            }
            
        }
    ?>

     

    Insert the block after price on the category page

    If you want to add a block after the price on the category page, and for this implementation, you can use the observer core_block_abstract_to_html_before.

    You can implement the logic with the below steps:
    File path: app/code/local/{namespace}/{yourmodule}/etc/config.xml

    <?xml version="1.0"?>
    <config>
        <global>
        <!-- ... -->
            <models> 
                <namespace_modulename>
                    <class>Namespace_Modulename_Model</class>
                </namespace_modulename>
            </models>
        </global>
        <frontend>
            <events>
                <core_block_abstract_to_html_before>
                    <observers>
                        <namespace_modulename>
                            <type>model</type>
                            <class>namespace_modulename/observer</class>
                            <method>insertBlock</method>
                        </namespace_modulename>
                    </observers>
                </core_block_abstract_to_html_before>
            </events>
        </frontend>
    </config>

    The next step is creating the observer and your template file.
    File path: app/code/local/{namespace}/{yourmodule}/Model/Observer.php

    <?php
    class Namespace_Modulename_Model_Observer
    {
        public function insertBlock($observer)
        {
            /** @var $_block Mage_Core_Block_Abstract */
            /*Get block instance*/
            $_block = $observer->getBlock();
            /*get Block type*/
            $_type = $_block->getType();
           /*Check block type*/
            if ($_type == 'catalog/product_price') {
                /*Clone block instance*/
                $_child = clone $_block;
                /*set another type for block*/
                $_child->setType('test/block');
                /*set child for block*/
                $_block->setChild('child', $_child);
                /*set our template*/
                $_block->setTemplate('filename.phtml');
            }
        }
    }
    ?>

    You can add the template to app/design/frontend/<package>/<theme>/filename.phtml .
    And finally, here is a template filename.phtml code:

    <?php echo $this->getChildHtml('child') ?>

     

    Magento 2: Run your JavaScript code after rendered KnockoutJS all elements in a page

    If you are using require([“jquery”, “domReady!”], function($){} function or jQuery(window).load() function, Using this code, mostly your custom javascript code executes before the knockout element render.

    Knockout js has afterRender event.

    See below simple demo for afterRender function.

    <div class="ko-concetp">
     <div data-bind="afterRender: loadJsCustomAfterKoRender"></div>
    </div>
    

    Here, we have to define afterRender in the data-bind syntax for use in a knockout as shown above.
    loadJsCustomAfterKoRender is the function which we need to call after knockout rendered completely.

    Now, create a function loadJsCustomAfterKoRender in the js file as below:

    loadJsCustomAfterKoRender: function(){
     // write your custom script logic here
    }

    The above logic will solve the problem.

    CONTACT US to get Magento programming solutions by hiring a certified Magento expert.

    How to show CMS static block in Magento 2

    Are you wondering, how to show CMS Static Block in Magento 2?

    Here, you will find effective instruction about this topic.

    Call from Phtml File:

    echo $this->getLayout()
              ->createBlock('MagentoCmsBlockBlock')
              ->setBlockId('your_block_identifier')
              ->toHtml();

    Call from CMS page or block:

    {{block class="MagentoCmsBlockBlock" block_id="your_block_identifier"}}
    

    Call from XML File:

    <referenceContainer name="content">
        <block class="MagentoCmsBlockBlock" name="block_identifier">
            <arguments>
                <argument name="block_id" xsi:type="string">block_identifier</argument>
            </arguments>
        </block>
    </referenceContainer>

    Hope this helps you!

    How to Override a Helper File in Magento 2

    To override Magento 2 Helper file, follow below steps.

    First, you need to create a di.xml file at below desired location.

    Go to Vendor/Extension/etc/di.xml And add the following code into di.xml

    Magento 2: Creating and Calling Custom Popup using Modal

    Here we are discussing how to create and call custom popup using Magento 2’s Popup Modal Library.

    You should create a module first, then after create a requirejs-config.js file at app/code/CustomVendor/CustomModule/view/frontend/

    var config = {
        paths: {            
             'myjs': "CustomVendor_CustomModule/js/customfile"
          },   
        shim: {
        'myjs': {
            deps: ['jquery']
        }
      }
    }

    You need to create customfile.js at app/code/CustomVendor/CustomModule/view/frontend/web/js/

    <script>
        require(
            [
                'jquery',
                'Magento_Ui/js/modal/modal'
            ],
            function(
                $,
                modal
            ) {
                var options = {
                    type: 'popup',
                    responsive: true,
                    innerScroll: true,
                    buttons: [{
                        text: $.mage.__('Continue'),
                        class: 'mymodal1',
                        click: function () {
                            this.closeModal();
                        }
                    }]
                };
    
                var popup = modal(options, $('#custompopup'));
                $("#click-here").on('click',function(){
                    $("#custompopup").modal("openModal");
                });
            }
        );
    </script>

    Add following code in your phtml file:

    <div data-mage-init='{"myjs": {}}'>
        <a href="#" id="click-here">Click Here</a>
    </div>
    
    
    <div id="custompopup" >
        This is custom popup using magento popup modal.
    </div>

     

    Magento 2 controller override

    It is a quite simple tutorial with 2 steps:

    Step 1:

    Create di.xml file at app/code/[Name space]/[Your Module]/etc

    <?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
       <preference for="MagentoCmsControllerIndexIndex" type="[Name Space][Your Module]ControllerCmsIndex" />
    </config>

    In this example, we will rewrite controller Magento/Cms/Controller/Index/Index. In which, [Name Space][Your Module]ControllerCmsIndex will be used to override MagentoCmsControllerindexIndex –the homepage in original Magento 2.

    Step 2: Define an overriding controller class

    You need to create Index.php in app/code/[Name Space]/your Module]/Controller/Index

    <?php
    
    namespace [Name Space][Your Module]ControllerIndex;
    class Index extends MagentoCmsControllerIndexIndex
    {
    public function execute($coreRoute = null)
    {
        // todo
    
    }
    }

    Done! I’m sure that you can follow this tutorial without any difficulty.