:::: MENU ::::
Posts tagged with: php

Magento 2 retrieve admin url

Today we talk about how in Magento 2 retrieve admin url. This tutorial included how to get admin url in case you forgot about that. This tutorial show how can you get your admin url from command and also from file. So let start with our example.

File system:

You can also retrieve the the Magento 2 Admin URL in /app/etc/env.php. Example of the relevant file content:

'backend' =>
    array (
       'frontName' => 'admin_test',
    ),

Using Command Line Interface(CLI):

Run the following command to retrieve admin url information.

php bin/magento info:adminuri
Author: Qaisar Satti
Category: Magento 2
Last Modified: May 7, 2018


Magento 2 use plugin

Today we talk about how in Magento 2 use plugin. The plugin or Interceptor is a class the modify the behaviour of public class method by interceptions. The plugin give use three option to use After methods, Before methods and Around Method. This tutorial included example of how to add button on sales order view page. Now Following this example you can use plugin with any public class method in magento 2. So let start with our example.

Create di.xml

First create the di.xml in QaisarSatti/HelloWorld/etc/di.xml if it is not already created. If it is already create just add the plugin code.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="\Magento\Sales\Block\Adminhtml\Order\View">
        <plugin name="QaisarSatti_HelloWorld::AddButtonOrderView" type="QaisarSatti\HelloWorld\Plugin\AddButtonOrderView" />
    </type>
</config>

Create AddButtonOrderView.php

Now we create AddButtonOrderView.php in following directory QaisarSatti\HelloWorld\Plugin. Inject \Magento\Sales\Block\Adminhtml\Order\View in your method to get block obejct.

namespace QaisarSatti\HelloWorld\Plugin;

class AddButtonOrderView
{
   

    public function beforeSetLayout(\Magento\Sales\Block\Adminhtml\Order\View $object)
    {
       
   
            $message = __('Are you sure you want to perform this action?');
  $url = $object->getUrl('addurlhere', ['order_id' =>$object->getOrderId()]);
            $object->addButton(
                'UnCancel',
                [
                    'label' => __('Test Buttonl'),
                    'onclick' => "confirmSetLocation('{$message}', '{$url}')"
                ]
            );
   
    }
}

Note: Following this example you can use plugin with other public class methods too.

Author: Qaisar Satti
Category: Magento 2
Last Modified: April 25, 2018


Magento 2 create product programmatically

Today we discussed how in Magento 2 create product programmatically. This tutorial includes the process of creating a simple product, set image to product and set quantity to product. So lets start with creating a simple product. We can do this in two ways- one is creating product with factory method and other is creating product with object manager.

Create Product with Factory Method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function createProduct()
    {
       
        $_product = $this->_productloader->create();
        $_product->setName('First Test Product');
        $_product->setTypeId('simple');
        $_product->setAttributeSetId(4);
        $_product->setSku('test-SKU');
        $_product->setWebsiteIds(array(1));
        $_product->setVisibility(4);
        $_product->setPrice(array(1));
        $_product->setImage('/simpeproduct/test.jpg');
        $_product->setSmallImage('/simpeproduct/test.jpg');
        $_product->setThumbnail('/simpeproduct/test.jpg');
        $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

        $_product->save();
        echo $_product->getId();
    }

Update Product with factory method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function updateProduct()
    {
       
        $_product = $this->_productloader->create()->load(2047);
        $_product->setName('First Test Product Updated');
        $_product->save();
    }

Create Product with Object manager

 <?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $objectManager->create('Magento\Catalog\Model\Product');
    $_product->setName('First Test Product');
    $_product->setTypeId('simple');
    $_product->setAttributeSetId(4);
    $_product->setSku('test-SKU');
    $_product->setWebsiteIds(array(1));
    $_product->setVisibility(4);
    $_product->setPrice(array(1));
    $_product->setImage('/simpeproduct/test.jpg');
    $_product->setSmallImage('/simpeproduct/test.jpg');
    $_product->setThumbnail('/simpeproduct/test.jpg');
    $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

$_product->save();
echo $_product->getId();

Update Product with Object manager

Now our custom product is created. Now we will update product. So doing with following example just.

            $_product = $objectManager->create('Magento\Catalog\Model\Product')->load(2047);
    $_product->setName('First Test Product Updated');
    $_product->save(); ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 19, 2018


Magento 2 reset admin password

Today we discuss how in Magento 2 reset admin password. This topic include how to reset admin password with sql query, reset password through command line interface (cli). Sometime you forgot the admin password so today we discuss how to reset your admin password. There are two ways to do that. First go to database and reset your with sql query and second create new user from command line and then login and reset the password from admin panel.

Reset with Query

Change test123 to your required password.

UPDATE `admin_user` SET `password` = CONCAT(SHA2('xxxxxxxxtest123', 256), ':xxxxxxxx:1') WHERE `username`= 'admin'

Reset From Cli

Create new user and login to admin panel and change you old user password.

<path_to_magento> php bin/magento admin:user:create --admin-user="admin" --admin-password="123123q" --admin-email="[email protected]" --admin-firstname="Admin" --admin-lastname="Admin"
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 4, 2018


Magento 2 Render WYSIWYG content

Today we discuss how in Magento 2 Render WYSIWYG content. This topic will cover how to render wysiwyg editor content.There are two ways to render the WYSIWYG content. First Zend_Filter_Interface and second Using the \Magento\Cms\Model\Template\FilterProvider.

Using Zend Interface

namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $contentProcessor;
public function __construct(
    \Zend_Filter_Interface $templateProcessor,
) {
 
    $this->contentProcessor = $contentProcessor;
}
public function processContent($content)
{
    return $this->contentProcessor->filter($content);
}
}

Now Add block reference in di.xml

<type name="QaisarSatti\HelloWorld\Block\HelloWorld">
    <arguments>
        <argument name="contentProcessor" xsi:type="object">Magento\Widget\Model\Template\Filter</argument>
    </arguments>
</type>

Now call method from phtml

<?php echo $block->processContent($content);?>

Using CMS Model

namespace QaisarSatti\HelloWorld\Block;

class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $contentProcessor;
public function __construct(
    \Magento\Cms\Model\Template\FilterProvider $contentProcessor,
) {
 
    $this->contentProcessor = $contentProcessor;
}
public function processContent($content)
{
    return $this->contentProcessor->getPageFilter()->filter($content);
}
}

Now call method from phtml

<?php echo $block->processContent($content);?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: April 4, 2018


Magento 2 create basic module frontend part 4

As we finished with the basic module structure and admin part we move to Magento 2 create basic module frontend .Now this tutorial will be cover the create frontend router, create layout file, create frontend controller, create frontend block, add custom pagination. Now we start with frontend.

Create frontend router

Create routes.xml in following directory

QaisarSatti\HelloWorld\etc\frontend\

<?xml version="1.0"?>
<!--
/**
* Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
     <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
        <router id="standard">
            <route id="helloworld" frontName="helloworld">
                <module name="QaisarSatti_HelloWorld" />
            </route>
        </router>
    </config>

Create frontend controller

Create Index.php in following directory

QaisarSatti\HelloWorld\Controller\Index\

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

namespace QaisarSatti\HelloWorld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action

{

    public function execute()
    {  
       
        $this->_view->loadLayout();
        $this->_view->renderLayout();
    }

}

Create layout file

Create helloworld_index_index.xml in following directory

QaisarSatti\HelloWorld\etc\frontend\

<?xml version="1.0"?>
<!--
/**
* Hello World
   *
   * @category    QaisarSatti
   * @package     QaisarSatti_HelloWorld
   * @author      Muhammad Qaisar Satti
   * @Email       [email protected]
   *
*/
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceContainer name="content">
                <block class="QaisarSatti\HelloWorld\Block\HelloWorld" name="HellosWorld" template="QaisarSatti_HelloWorld::HelloWorld.phtml"></block>
            </referenceContainer>
        </body>
    </page>

Create frontend block

Create HelloWorld.php in following directory

QaisarSatti\HelloWorld\Block\

<?php
/**
 * Hello World
    *
    * @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 $_coreRegistry = null;
    protected $_collectionFactory;
    protected $_productsFactory;
    protected $_helloworldFactory;
   public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \QaisarSatti\HelloWorld\Model\ResourceModel\HelloWorld\CollectionFactory $helloworldFactory,
       array $data = []
   ) {
 
       $this->_coreRegistry = $registry;
       $this->_helloworldFactory = $helloworldFactory;
       parent::__construct($context, $data);
   }
   public function getHelloCollection()
        {
          $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
           //get values of current limit
          $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 5;

          $helloCollection = $this->_helloworldFactory->create();
          $helloCollection->setPageSize($pageSize);
          $helloCollection->setCurPage($page);
          return $helloCollection;
        }
   public function _prepareLayout()
   {
   
       parent::_prepareLayout();
       $this->pageConfig->getTitle()->set(__('Sample Post'));

       if ($this->getHelloCollection()) {
            $pager = $this->getLayout()->createBlock('Magento\Theme\Block\Html\Pager','qaisarsatti.blog.pager')->setAvailableLimit(array(5=>5,10=>10,15=>15,20=>20));
            $pager->setShowPerPage(true);
            $pager->setCollection($this->getHelloCollection());
            $this->setChild('pager', $pager);
            $this->getHelloCollection()->load();
        }
        return $this;
   }
   public function getPagerHtml(){
        return $this->getChildHtml('pager');
    }


}

Create frontend phtml

Create HelloWorld.phtml in following directory

QaisarSatti\HelloWorld\view\frontend\templates\

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

$blogCollection = $block->getHelloCollection();
foreach ($blogCollection as $blog) {

    echo $blog->getTitle().'<br />';
    echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$blog->getContent().'<br />';
}

 if ($block->getPagerHtml()): ?>
<div class="order-products-toolbar toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>
<?php endif ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: February 9, 2018


Magento 2 get current product information

Today we talk about how to get Magento 2 current product information like product id, product name and other information on product page. Magneto 2 have feature of registry to store data. That is use to store data between execution of data. Like you want to set data in controller and use it in block or model the registry is best option for that. So let start with getting the product data from registry. Now i use HelloWorld module block example for getting current product.
Create a Block

<?php
namespace QaisarSatti\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
    protected $registry;

    public function __construct(  
        \Magento\Framework\Registry $registry,

    )
    {      
        $this->registry = $registry;

    }


    public function getCurrentProduct()
    {      
        return $this->registry->registry('current_product');
    }  

}
?>

Get product information In your phtml file

<?php
  $currentProduct = $block->getCurrentProduct();
            echo $currentProduct->geId();
            echo $currentProduct->geName();
 ?>

If you want to get in current product information in phtml you can use following code.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $currentProduct = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product information
    echo $currentProduct>getId();
    echo $currentProduct>getName();
?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: January 17, 2018


Pages:1234