:::: MENU ::::
Posts tagged with: magento 2

Magento 2 Get base url in js

This tutorial is about magento 2 Get base url in js file. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how to get base url from js file in magento 2. Above all if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.

So lets start our tutorial and focus on our topic. For example if you want to get base url from .js file and append it with your module controller link from. How can we do it? It is almost impossible to use block to get the base url.

Get base url

So we will look at the way how we can get base url. to do that,paste the following code in your routes.xml file

define([

   'mage/url'
], function (url) {

  var linkUrl = url.build('test/test/test');
  console.log(linkUrl);
});

Where frontname is your routes.xml file frontname.

Since it is necessary,you have to pass your frontname from routes.xml file instead of module name(namespace_module).

Furthermore you can lookup your routes.xml file from

app/code/QaisarSatti/HelloWorld/etc/frontend/routes.xml

It might work for some and might not for others.

Further more Add this code in phtml file:

<input type="hidden" value="<?php echo $this->getUrl(); ?>" id="baseUrl"/>

having done that you can use this base url in js file by id :

$("#baseUrl").val();

It is a quite useful and tested trick. So i thought to share it.

There is another approach for this task.Having said that it may too be useful.

You should pass url to js(widget).Url is a parameter of js widget.And put script below to your template where you want to.

<script type="text/x-magento-init">
{
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "yourWidget": {
                    "dataUrl": "<?php echo $block->getBaseUrl(); ?>"
                }
            }
        }
    }
}
</script>

Similarly in javascript widget, you can access to dataUrl by below code.

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            console.log(this.dataUrl);
        }
    });
});

Another simple approach is

<script>
window.testUrl = <?php echo json_encode($block->getBaseUrl()); ?>
</script>

Using your custom js you can have easy access to window.testUrl global variable.

That’s it from this tutorial. I hope it serves the purpose.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

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


Magento 2 Call Helper method in phtml

This tutorial is about Magento 2 Helper method in phtml.i.e Helper method in magento 2. First of all i assume you are familiar with magento 2. And if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.

lets start our tutorial.Suppose you want to call a Helper method in template(.phtml) file.How can you do it?. We will discuss it briefly in this tutorial.

It is not a good practice to use helper calls directly in the template.Because it introduces an undeclared dependency. If you want to do this properly you should only call in the template only methods from the block that renders it.Rather you can have your helper instance provided as a dependency to the block that renders the template and create a method in your block that calls the helper and call that method in the template.

You can defined your block like:

protected $helperData;
public function __construct(
     ....
    \QaisarSatti\HelloWorld\Helper\Data $helperData,
    ....
) {
    ....
    $this->helperData = $helperData;
    ....
}

public function doSomething()
{
    return $this->helperData->doSomething();
}

Finally you can call this block like:

$block->doSomething()

Where block something in my case is just for understanding.You will use your own function name.

Similarly there is another way of doing it.Lets have a look at the code:

$helper = $this->helper('QaisarSatti\HelloWorld\Helper\Data');
$values = $helper->YourHelperMethod();

Furthermore you have to write the whole class name in helper as below:

$this->helper('QaisarSatti\HelloWorld\Helper\Data')

You can use it in phtml file using above code.

Further more with some modifications, there is another approach of doing it.

Lets have a look at it.

Likewise you can look at the directory,in which this code is implemented:

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/Block/Test.php

  <?php
namespace QaisarSatti\HelloWorld\Block;

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

protected $_helper;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    array $data = [],
    \QaisarSatti\HelloWorld\Helper\Data $helper
) {
    parent::__construct($context, $data);

    $this->_helper = $helper;
}

public function getEnable(){
        return $this->_helper->getEnable();
    }

}

Similarly in

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/view/frontend/templates/homehorizontalwidget.phtml

you can modify:

 <?php  echo $block->getEnable(); ?>

Furthermore in

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/Helper/Data.php

. we can use below code:

<?php
namespace QaisarSatti\HelloWorld\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper {

    /** * @var \Magento\Framework\App\Config\ScopeConfigInterfac
        */

    protected $_scopeConfig;
    CONST ENABLE = 'helloworld/general/enable_module';


    public function __construct( \Magento\Framework\App\Helper\Context $context,
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig ) {

             parent::__construct($context); $this->_scopeConfig = $scopeConfig;
    }

    public function getEnable(){
        return $this->_scopeConfig->getValue(self::ENABLE);
    }

}

Similarly in

/var/www/html/magento2/app/code/QaisarSatti/HelloWorld/etc/adminhtml/system.xml

System configurations are created.

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


Magento 2 call any block function in phtml

This tutorial is about magento 2 call block function in phtml. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how in magento 2 call any block function in phtml. Above all if you are not familiar and are looking for basics please look for magento 2 basic tutorials.

Seems like i have conveyed my message so lets start our tutorial and focus on our topic. For example if you want to call your custom block function in product list.phtml?.How can we do it? I will try to explain it in a simple way.

Call custom block funtion

Lets have a look at the code.
For example your block class is as below

<?php
namespace QaisarSatti\HelloWorld\Block;
use Magento\Framework\View\Element\Template;

class Test extends Template
{
    public function getMyCustomMethod()
    {
        return 'Get Your custom method';
    }
}

Then in any phtml file,you can use the following code to get method of this block.

<?php
$blockObj= $block->getLayout()->createBlock('QaisarSatti\HelloWorld\Block\Test');
echo $blockObj->getMyCustomMethod();
?>

That is how it can be done.Certainly, i have tried to explain these codes and their logic in a simple way, i hope they help you learn in an easy and better way. That’s it from this tutorial.

Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 4, 2018


list all customer groups in Magento 2

Today we will learn how to list all customer group in magento 2. Getting the complete list of customers/users means displaying a list of all the customer groups including not logged in group as well.

So,you can get the complete list of customer groups,using following code:

Factory Method:

namespace QaisarSatti\Module\Block;

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

  protected $groupCollection;  


  public function __construct(
     
        \Magento\Customer\Model\ResourceModel\Group\CollectionFactory $groupCollection

    ) {


        $this->groupCollection = $groupCollection;
     
    }
    public function getCustomerGroup()
    {
       
        return $this->groupCollection->create()->toOptionArray();
    }

}

Object Manager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$groupOptions = $objectManager->get('\Magento\Customer\Model\ResourceModel\Group\Collection')->toOptionArray();

$fieldset->addField(
    'customer_group',
    'multiselect',
    [
        'name' => 'customer_group[]',
        'label' => __('Customer Group'),
        'title' => __('Customer Group'),
        'values' => $groupOptions,
        'disabled' => $isElementDisabled
    ]
);

One can also use the following class:

Magento\Customer\Model\Customer\Source\Group

This class provides the

toOptionArray

method which can be used to get an array of customer groups.

That’s it for this tutorial. I hope it will help you in a certain and easy way.

Author: Qaisar Satti
Category: Magento 2
Last Modified: October 2, 2018


Magento 2 admin panel Unable to sign in or Account temporarily disabled

Today we will discuss about how you can solve the issue of magento 2 admin panel unable to sign in or account temporarily disabled. This mainly occurs due to secure functionality of magento 2. Magento 2 have introduced account disabled functionality keeping in mind the security of business. if you tried the wrong password repeatedly in admin panel login. Then you account got locked and temporary disabled. There are various methods to do so but we will discuss few here.

Lets have a look at the first method, in which you will learn to unlock and access the root folder

Unlock admin user

One can unlock the temporarily disabled account by going to Magento 2 root folder SSH and running the
the following command:

php bin/magento admin:user:unlock admin

There is another way of solving this problem but that might work for some and might not work for others. But is worth giving a try.

By resetting the username and password

For doing so do the following

sudo php bin/magento admin:user:create --admin-user="pearlbells" --admin-password="pear122l**all" --admin-email="[email protected]" --admin-firstname="Admin" --admin-lastname="Admin"

As i told you earlier there are many ways but we just discussed few simple and efficient methods.I Hope they will serve the purpose ad be useful.

Author: Qaisar Satti
Category: Magento 2
Last Modified: September 26, 2018


Magento 2 get base directory

Today we discuss about Magento 2 get base directory .This tutorial include how to get base directory like media and other directories. There are two ways to do it. One is factory method and other is use object manager. So let start with our example.

Factory Method

In this example we will get base directory of media.

<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email [email protected]
*
*/

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $directoryList;

public function __construct(
\Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    $this->directoryList=$directoryList
}
public function getbaseDir()
{
   return $this->_directorylist->getPath('media');

}

}

Object Manager

In this example we will get base directory of media. Using object manager is not recommended.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$dir = $objectManager->create('Magento\Framework\App\Filesystem\DirectoryList');
$mediaPath = $dir->getPath('media');
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 20, 2018


Magento 2 get media path

Today we discuss about Magento 2 get media path .This tutorial include how to get media path in your block or phtml file. There are two ways to do it. One is factory method and other is use object manager. So let start with our example.

Factory Method

In this example we will get media path. First your need to inject \Magento\Store\Model\StoreManagerInterface.

<?php
/**
* Simple Hello World Module
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
* @Email [email protected]
*
*/

namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $storeManager;

public function __construct(
   
    \Magento\Store\Model\StoreManagerInterface $storeManager,
   
) {
   
    $this->storeManager = $storeManager;
   
}

public function getMediaUrl()
{
    return $mediaUrl = $this->storeManager
                     ->getStore()
                     ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
   
}


}

Object Manager

In this example we will get media path. Using object manager is not recommended.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
                    ->getStore()
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 20, 2018


Pages:1234567...15