Techzento https://techzento.com Web Design and Web Development Company Mon, 14 Nov 2022 03:50:04 +0000 en-US hourly 1 https://techzento.com/wp-content/uploads/2021/01/fav-1.png Techzento https://techzento.com 32 32 How to get country collection in magento2 https://techzento.com/how-to-get-country-collection-in-magento2/ Sun, 13 Nov 2022 20:55:44 +0000 http://localhost/web-developer/?p=320 _countryFactory= $countryFactory; } Then in your class you can do: public function getAllOptions() { return $options = $this->getCountryCollection()->toOptionArray(); } public […]]]> To get country collection in toOptionArray, you need to add following code in your file:
First you need to inject a \Magento\Directory\Model\ResourceModel\Country\CollectionFactory in your class constructor:

    protected $_countryFactory;
    public function __construct(
        \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryFactory
    ) {
        $this->_countryFactory= $countryFactory;
    }

Then in your class you can do:

 public function getAllOptions()
    {
        return $options = $this->getCountryCollection()->toOptionArray();
    }
    public function getCountryCollection()
    {
        $collection = $this->_countryFactory->create()->loadByStore();
        return $collection;
    }

Full Code:

protected $_countryFactory;
public function __construct(
     \Magento\Directory\Model\ResourceModel\Country\CollectionFactory $countryFactory
) {
     $this->_countryFactory= $countryFactory;
}
public function getAllOptions()
{
    return $options = $this->getCountryCollection()->toOptionArray();
}
public function getCountryCollection()
{
    $collection = $this->_countryFactory->create()->loadByStore();
    return $collection;
}
public function getOptionValue($value) 
{ 
    foreach ($this->getAllOptions() as $option) {
        if ($option['value'] == $value) {
            return $option['label'];
        }
    }
    return false;
}

Run php bin/magento setup:di:compile when you add any dependency injection.Because without php bin/magento setup:di:compile it throws error in code.

]]>
How to load quote by quote id in Magento 2 https://techzento.com/how-to-load-quote-by-quote-id-in-magento-2/ Thu, 26 Sep 2019 02:23:50 +0000 http://localhost/web-developer/?p=317 In Magento 2 you can load Quote by Dependency Injection and by ObjectManager. My preferred method is Dependency Injection, but you can also do it by ObjectManager.Try to avoid the ObjectManager method because it is not a good practice for learning. But in given below examples you can see in both method.

By Dependency Injection

First you need to inject a \Magento\Quote\Model\QuoteFactory in your class constructor:

namespace Awa\Demo\Controller\Adminhtml\Quote;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;

class Demo extends \Magento\Backend\App\Action
{
     protected $quoteFactory;

     public function __construct(
          Context $context,
          \ \Magento\Quote\Model\QuoteFactory $quoteFactory
     ) {
         $this->quoteFactory = $quoteFactory;
         parent::__construct($context);
    }
   public function execute()
   {
      $quoteId=12;
      $quote = $this->quoteFactory->create()->load($quoteId);
   }
}

By ObjectManager

Try to Avoid this Method.

$quoteId = 12;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager ->create('Magento\Quote\Model\Quote')->loadByIdWithoutStor‌​e($quoteId);

Run php bin/magento setup:di:compile when you add any dependency injection.Because without php bin/magento setup:di:compile it throws error in code.

Hope this will helps you!

]]>
Magento 2: Assign/Remove Products from Categories Programmatically https://techzento.com/magento-2-assign-remove-products-from-categories-programmatically/ Thu, 26 Sep 2019 02:23:08 +0000 http://localhost/web-developer/?p=315 This article shows how you can programmatically assign a product to multiple categories and how you can remove a product from a category in Magento2.

The below things are done in the below code:

  • Initialize the object manager.
  • Set the area code as adminhtml as we are editing the product.
  • Define the logger to log information about the delete process. Zend Logger is used.
<?php
error_reporting(1);
set_time_limit(0);
ini_set('memory_limit', '2056M');
use Magento\Framework\App\Bootstrap;
/**
 * If your external file is in root folder
 */
require __DIR__ . '/app/bootstrap.php';
 
/**
 * If your external file is NOT in root folder
 * Let's suppose, your file is inside a folder named 'xyz'
 *
 * And, let's suppose, your root directory path is
 * /var/www/html/magento2
 */
// $rootDirectoryPath = '/var/www/html/magento2';
// require $rootDirectoryPath . '/app/bootstrap.php';
 
$params = $_SERVER; 
$bootstrap = Bootstrap::create(BP, $params); 
$objectManager = $bootstrap->getObjectManager();
 
// Set Area Code
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); // or \Magento\Framework\App\Area::AREA_FRONTEND, depending on your need
 
// Define Zend Logger
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/assign-remove-product-to-category.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

Here we need product SKU for this operation, if you have product ID then follow below instruction to get product SKU
Get Product SKU from Product ID:

$productId = 897; // product ID
$productRepository = $objectManager->get('Magento\Catalog\Api\ProductRepositoryInterface');
$product = $productRepository->getById($productId);
$sku = $product->getSku(); // product SKU

Assign a Product to Multiple Categories:

/**
 * Assign product to categories
 */ 
$categoryIds = ['10', '18', '38'];
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface'); 
$categoryLinkRepository->assignProductToCategories($sku, $categoryIds);

Remove a Product from a Category:

/**
 * Remove product from category
 */ 
$categoryId = 10;
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');
$categoryLinkRepository->deleteByIds($categoryId, $sku);

Hope this will helps you!

]]>
Magento 2: Setup Multiple Stores and Websites https://techzento.com/magento-2-setup-multiple-stores-and-websites/ Thu, 26 Sep 2019 02:16:50 +0000 http://localhost/web-developer/?p=311 Here you learn how you can setup multiple stores and multiple websites in Magento 2.
we are having a different domain or sub-domain for the stores and websites.

Create/Add new stores and websites from Magento admin:

  1. Login to Magento admin panel
  2. Go to STORES -> All Stores
  3. Create Website
  4. Create Store
  5. And, then Create Store View

Assume that we have created the following Website/Store/Store view:

Website: base
Store: main_website_store
Store View: default

Website: base
Store: main_website_store
Store View: new

Website: wholesale_website
Store: wholesale_store
Store View: wholesale

This means that we have created 2 websites.

– One website is the base or main website which has two store views with code `default` and `new`.
– The other website is the wholesale website which has a single store view with code wholesale.

Here are the URLs that I want to use for my stores and website:

Default Store: example.com
New Store: new.example.com
Wholesale Website: wholesale.example.com

Link the URLs to the stores and website
To link the URLs to their respective stores and website, we can either add the code in the index.php file or in the .htaccess file.


Please note:
– You don’t need to update both files.
– You can either update .htaccess file or index.php file.
– Updating .htaccess file is recommended.

Adding code in .htaccess file
Add the following code at the end of the .htaccess file:

SetEnvIf Host .*new.example.com.* MAGE_RUN_CODE=new
SetEnvIf Host .*new.example.com.* MAGE_RUN_TYPE=store
 
SetEnvIf Host .*wholesale.example.com.* MAGE_RUN_CODE=wholesale_site
SetEnvIf Host .*wholesale.example.com.* MAGE_RUN_TYPE=website

Adding code in index.php file
By default, at the end of your index.php file, you will have the code something like this:

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);

We will update it like this:

switch($_SERVER['HTTP_HOST']) {
    case 'new.example.com':
        $mageRunCode = 'new';
        $mageRunType = 'store';
    break;
    case 'wholesale.example.com':
        $mageRunCode = 'wholesale_site';
        $mageRunType = 'website';
    break;
    default:
        $mageRunCode = 'base';
        $mageRunType = 'website';
}
$params = $_SERVER;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = $mageRunCode;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = $mageRunType;
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
 
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);

Hope this will helps you!

]]>
Magento 2 Get Product Collection https://techzento.com/magento-2-get-product-collection/ Thu, 26 Sep 2019 02:14:53 +0000 http://localhost/web-developer/?p=309 This blog shows how we can get product collection in Magento 2.

Using Dependency Injection (DI)
Below is a block class of my custom module (Mtutorials_HelloWorld). I have injected object of \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory class in the constructor of my module’s block class.

app/code/Mtutorials/HelloWorld/Block/HelloWorld.php

<?php
namespace Mtutorials\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;
 
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,        
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
    }
 
    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products
        return $collection;
    }
}
?>

As you can see in above code, I have addded limit to the product collection. I have selected only 3 products.
Now, we print the product collection in our template (.phtml) file.

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

Using Object Manager

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$appState = $objectManager->get('\Magento\Framework\App\State');
$appState->setAreaCode('frontend');
 
$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3); // selecting only 3 products
 
foreach ($collection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

Hope this will helps you!

]]>
Magento 2 Error 503 backend fetch failed https://techzento.com/magento-2-error-503-backend-fetch-failed/ Thu, 26 Sep 2019 02:10:09 +0000 http://localhost/web-developer/?p=303 503 backend fetch failed error
If the length of cache tags used by Magento exceed Varnish’s default of 8192 bytes, you can see HTTP 503 (Backend Fetch Failed) errors in the browser. The errors might display similar to the following:
To resolve this issue, increase the default value of the http_resp_hdr_len parameter in your Varnish configuration file. The http_resp_hdr_len parameter specifies the max header length within the total default response size of 323768 bytes.
If the http_resp_hdr_len value exceeds 32K, you must also increase the default response size using the http_resp_size parameter.

1. As a user with root privileges, open your Vanish configuration file:
CentOS 6: /etc/sysconfig/varnish
CentOS 7: /etc/varnish/varnish.params
Debian: /etc/default/varnish
Ubuntu: /etc/default/varnish

2. Edit varnish config file and search for http_resp_hdr_len parameter in this file and change this by following line:

-p http_resp_hdr_len=67000

And if you not found above parameter then add it after thread_pool_max.

See Below:

DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
     -f ${VARNISH_VCL_CONF} \
     -T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
     -p thread_pool_min=${VARNISH_MIN_THREADS} \
     -p thread_pool_max=${VARNISH_MAX_THREADS} \
     -p http_resp_hdr_len=67000\
     -p http_resp_size=98500 \
 -p workspace_backend=98500 \
     -S ${VARNISH_SECRET_FILE} \
     -s ${VARNISH_STORAGE}"

After this changes save file and restart server.

Hope this will helps you!

]]>
Magento 2 show address on customer register page https://techzento.com/magento-2-show-address-on-customer-register-page/ Thu, 26 Sep 2019 02:08:06 +0000 http://localhost/web-developer/?p=301 If you want to show customer address fields on registration form page. Than you need to set true to show.address.fields in your customer_account_create.xml. See Below Steps for this example:

1). First you need to Create below file in your custom theme:

app/design/frontend/Select_theme_folder/Magento_Customer/layout/customer_account_create.xml

2). Now put below code in this xml file.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="customer_form_register">
            <action method="setShowAddressFields">
                <argument name="show.address.fields" xsi:type="boolean">true</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Now save this file. and run below commands:
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
php bin/magento cache:clean

Hope this will helps you!

]]>
Magento 2 Get Currency Symbol from Currency Code https://techzento.com/magento-2-get-currency-symbol-from-currency-code/ Thu, 26 Sep 2019 02:05:37 +0000 http://localhost/web-developer/?p=299 Magento 2 has multiple methods to get Currency symbol.You can get it from Dependency Injection, or by ObjectManager. My preferred method is Dependency Injection, but you can also do it by ObjectManager. Remember: try to avoid the ObjectManager method because it is not a good practice for learning. But in given below examples you can see in both filter method.

By Dependency Injection

protected $CurrencySymbol;
 
public function __construct(
    \Magento\Framework\Locale\CurrencyInterface $CurrencySymbol
)
{
    $this->CurrencySymbol= $CurrencySymbol;
}
Now you can use below code in your function to get currency symbol.
$CurrencyCode='USD';
$this->CurrencySymbol->getCurrency($CurrencyCode)->CurrencyCode();

By ObjectManager

$ObjectManager = \Magento\Framework\App\ObjectManager::getInstance();
$CurrencyCode='USD';
$Symbol = $ObjectManager ->create('Magento\Directory\Model\CurrencyFactory')->create()->load($CurrencyCode);
echo $Symbol ->getCurrencySymbol();

By ObjectManager, you can get currency symbol in phtml file also.
Run php bin/magento setup:di:compile when you add any dependency injection. Because without php bin/magento setup:di:compile it throws error in code.

Hope this will helps you!

]]>
magento 2 Parse error: syntax error, unexpected ‘ ‘ (T_STRING) https://techzento.com/magento-2-parse-error-syntax-error-unexpected-t_string/ Thu, 26 Sep 2019 02:03:40 +0000 http://localhost/web-developer/?p=296 Parse error: syntax error, unexpected ‘ ‘ (T_STRING) This kind of error comes in two case.

Case 1:
This kind of error comes when some white space is present in your code.
Solution:
Remove white space from your code.

Case 2:
When you copy code from other source.
Solution:
When you copy code from some source, it includes special character and white space in the lines you have to remove these invisible special characters and white space from lines at beginning or ending.

Hope this will helps you!

]]>