CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other
Showing posts with label Magento 2. Show all posts
Showing posts with label Magento 2. Show all posts

18 May, 2022

Magento 2 Add Products To Category Programmatically

 Programing Coderfunda     May 18, 2022     Magento 2     No comments   

 When there are too many products, it might be difficult for online shoppers to browse the website and find what they are looking for. That’s why it’s important to divide and arrange products in different relevant categories.

To avoid uncategorized products bothering your customer experience, you can create multiple categories and add classified products into suitable ones to make optimized navigation for your website.

Magento 2 allows store admins to add and remove products from the category under Magento 2 Admin panel > CATALOG > Categories > Products in Categories section. However, in some cases, you need to add and remove products from categories programmatically.

In this article, I will show you how to assign and remove products from category programmatically through two methods:

  • Method 1: Using The Object Manager
  • Method 2: Using The Dependency Injection

Method 1: Using Object Manager

Add Products To Category Programmatically Using Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryIds = array('101','102');
$sku = '24-MB01';
$categoryLinkRepository->assignProductToCategories($sku, $categoryIds);

In this code snippet, there are two parameters passed including SKU of product and the array of categories to assignProductToCategories function. Please remember that this code snippet will remove the products from previously assigned categories and assign the products to newly passed categories.

For instance, SKU ‘24-MB01’ is assigned to category ids 99 and 100. After running above code SKU ‘24-MB01’ will be removed from category ids 99, 100 and assigned to 101, 102.

Remove Products From Category Programmatically Using Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');
$categoryId = 101;
$sku = '24-MB01';
$categoryLinkRepository->deleteByIds($categoryId,$sku);

In this code snippet, there are two parameters passed including category id and SKU to deleteBylds function. Please remember that after running this code snippet, the products will be removed from only that particular category and not from all previously assigned categories.

For instance, SKU ‘24-MB01’ is assigned to categories 99, 100, and 101. The above code snippet will remove SKU ‘24-MB01’ from category 101 only.

Method 2: Using The Dependency Injection

Using the below code snippet to add products to category programmatically:

<?php

public function assignProductsToCategory(){
	$this->getCategoryLinkManagement()
	->assignProductToCategories(
		$product->getSku(),
		$product->getCategoryIds() 
	);
}
private function getCategoryLinkManagement() { 

	if (null === $this->categoryLinkManagement) { 
		$this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
		->get('Magento\Catalog\Api\CategoryLinkManagementInterface'); 
		} 

	return $this->categoryLinkManagement; 
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to import products in category by programmatically in magento 2

 Programing Coderfunda     May 18, 2022     Magento 2     No comments   

 

Magento 2 Add Products To Category Programmatically


When there are too many products, it might be difficult for online shoppers to browse the website and find what they are looking for. That’s why it’s important to divide and arrange products in different relevant categories.

To avoid uncategorized products bothering your customer experience, you can create multiple categories and add classified products into suitable ones to make optimized navigation for your website.

Magento 2 allows store admins to add and remove products from the category under Magento 2 Admin panel > CATALOG > Categories > Products in Categories section. However, in some cases, you need to add and remove products from categories programmatically.

In this article, I will show you how to assign and remove products from category programmatically through two methods:

  • Method 1: Using The Object Manager
  • Method 2: Using The Dependency Injection

Method 1: Using Object Manager

Add Products To Category Programmatically Using Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');
$categoryIds = array('101','102');
$sku = '24-MB01';
$categoryLinkRepository->assignProductToCategories($sku, $categoryIds);

In this code snippet, there are two parameters passed including SKU of product and the array of categories to assignProductToCategories function. Please remember that this code snippet will remove the products from previously assigned categories and assign the products to newly passed categories.

For instance, SKU ‘24-MB01’ is assigned to category ids 99 and 100. After running above code SKU ‘24-MB01’ will be removed from category ids 99, 100 and assigned to 101, 102.

Remove Products From Category Programmatically Using Object Manager

<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryLinkRepository = $objectManager->get('\Magento\Catalog\Model\CategoryLinkRepository');
$categoryId = 101;
$sku = '24-MB01';
$categoryLinkRepository->deleteByIds($categoryId,$sku);

In this code snippet, there are two parameters passed including category id and SKU to deleteBylds function. Please remember that after running this code snippet, the products will be removed from only that particular category and not from all previously assigned categories.

For instance, SKU ‘24-MB01’ is assigned to categories 99, 100, and 101. The above code snippet will remove SKU ‘24-MB01’ from category 101 only.

Method 2: Using The Dependency Injection

Using the below code snippet to add products to category programmatically:

<?php

public function assignProductsToCategory(){
	$this->getCategoryLinkManagement()
	->assignProductToCategories(
		$product->getSku(),
		$product->getCategoryIds() 
	);
}
private function getCategoryLinkManagement() { 

	if (null === $this->categoryLinkManagement) { 
		$this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
		->get('Magento\Catalog\Api\CategoryLinkManagementInterface'); 
		} 

	return $this->categoryLinkManagement; 
}
by : mageplaza . com
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to Import Categories in Magento 2 Programmatically

 Programing Coderfunda     May 18, 2022     Magento 2     No comments   

 

Magento 2: Import a category with its subcategories programmatically


Categories are essential for creating an efficient catalog and customer navigation so that users can easily find the products they want on your website.

Each product should be assigned to at least one category. Categories are a helpful way to sort and arrange your products. The diagram below represents the structure of the category.

Magento 2 categories with subcategories

The Magento 2 Import/Export function is one of the best resolutions for all stores to simplify numerous tasks in the manual back-end. These features become more essential and useful for Magento merchants.

New call-to-action

Does Default Magento 2 Open Source Support Import Categories?

The answer is definitely, no. In default Magento 2, the admin creates categories one by one, complete with the related data in each category. In the case of migrating to Magento 2, or when updating or moving to a new website, manually creating categories would be such a time-consuming work that not every business would tolerate it.

The below script helps you to import each category with its subcategories simultaneously without the compulsory need of the parent category ID. Instead of that, we can use the parent category name.

Create a custom module as shown in the file structure below.

Note: Please take a backup of your data and check with your technical developer before running the code.

Magento 2 categories with subcategories

Step 1: Create 

app/code/DCKAP/CategoryImport/view/frontend/layout/categoryimport_index_index.xml

	
		
		
			
		
	

Step 2: Create a form to import a CSV.

app/code/DCKAP/CategoryImport/view/frontend/templates/categoryimport.phtml

CSV File:

 

Step 3: Create a controller to read and import the CSV.

app/code/DCKAP/CategoryImport/Controller/Index/Index.php

_pageFactory=$pageFactory;
		$this->_categoryFactory=$categoryFactory;
		$this->_category=$category;
		$this->_repository=$repository;
		$this->csv=$csv;
		return parent: :__construct($context);
	}
	public function execute() {
		$post=$this->getRequest()->getFiles();
		if($post) {
			if(isset($post['file_upload']['tmp_name'])) {
				$arrResult=$this->csv->getData($post['file_upload']['tmp_name']);
				foreach ($arrResult as $key=> $value) {
					if ($key > 0) {
						// to skip the 1st row i.e title
						$parentid=2;
						if(is_string($value[1])) {
							$categoryTitle=$value[1]; // Category Name
							$collection=$this->_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in'=> $categoryTitle]);
							if ($collection->getSize()) {
								$parentid=$collection->getFirstItem()->getId();
							}
						}
						else if(is_int(($value[1]))) $parentid=$value[1];
						//echo $parentid."
";//For reference
						$data=[ 'data'=>[ "parent_id"=>$parentid,
						'name'=>$value[2],
						"is_active"=>true,
						"position"=>10,
						"include_in_menu"=>true,
						]];
						$checkCategory=$this->_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in'=> $value[2]])->addFieldToFilter('parent_id', ['in'=> $parentid]);
						if( !$checkCategory->getData()) {
							$category=$this->_categoryFactory->create($data);
							$result=$this->_repository->save($category);
						}
					}
					$this->messageManager->addSuccessMessage('Category Imported Successfully');
				}
			}
		}
		$this->_view->loadLayout();
		$this->_view->renderLayout();
	}
}

Run this module:

http://localhost/magento/categoryimport/

Magento 2 categories with subcategories

The CSV format must be as shown below.

Click here to get a sample CSV.

In this CSV, your header will be what you want and the first column should be a serial number. The second column must be either a parent/root category ID or name, and the third column must be the name of the category.

************************ Import CSV File ************************

Sample CSV Format

S.NoParent Category ID/NameCategory
12Mobile
2MobileSamsung
3MobileOppo
4MobileVivo
5SamsungSamsung J Pro
6SamsungSamsung a 10
7OppoOppo Youth
8OppoOppo k1
9VivoVivo v5 plus
10VivoVivo v9

And finally, you can now simultaneously import each category with its subcategories. If you found this blog helpful, then please do let us know if you have any queries.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

15 April, 2022

Create a CSV file in Magento 2

 Programing Coderfunda     April 15, 2022     Magento 2     No comments   

In this blog, I will make sense of, how to make a CSV document in magentoMagento 2. CSV (Comma Separated Value) is one of the most well-known methods for bringing in/sending out information.

You can undoubtedly make a CSV document with PHP record compose because the arrangement of CSV record is exceptionally basic; every segment is isolated with a comma and each column is isolated with a new line. In any case, I will show how Magento gets it done or you can say the suggested way in Magento 2.


<?php
namespace Webkul\Csv\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

class CreateCsv extends Action
{
    public function __construct(
        Context $context,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Customer\Model\CustomerFactory $customerFactory
    ) {
        $this->customerFactory = $customerFactory;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        parent::__construct($context);
    }
 
    public function execute()
    {
        $filepath = 'export/customerlist.csv';
        $this->directory->create('export');
        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();

        $header = ['Id', 'Name', 'Email'];
        $stream->writeCsv($header);

        $collection = $this->customerFactory->create()->getCollection();
        foreach ($collection as $customer) {
            $data = [];
            $data[] = $customer->getId();
            $data[] = $customer->getName();
            $data[] = $customer->getEmail();
            $stream->writeCsv($data);
        }
    }
}

This will create a customerlist.csv file under var/export folder. Here we have written header data in the first row and all the customcustomerers data are written through the foreach loop.

If you want to know how can you download this CSV file programmatically then please check out our blog “Programmatically Download File in Magento 2”.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

CSV File Download Programmatically in Magento 2

 Programing Coderfunda     April 15, 2022     Magento 2     No comments   

 CSV File Download Programmatically in Magento 2

Please check the below code,

<?php
namespace Webkul\Csv\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

class GetFile extends Action
{
    public function __construct(
        Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory
    ) {
        $this->fileFactory = $fileFactory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        $filepath = 'export/customerlist.csv';
        $downloadedFileName = 'CustomerList.csv';
        $content['type'] = 'filename';
        $content['value'] = $filepath;
        $content['rm'] = 1;
        return $this->fileFactory->create($downloadedFileName, $content, DirectoryList::VAR_DIR);
    }
}

Hi Guys! if you want to create CSV file programmatically in Magento 2 . Create a CSV file in Magento 2



Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

30 March, 2022

Admin Session Lifetime | Adobe Commerce 2.4

 Programing Coderfunda     March 30, 2022     Magento, Magento 2     No comments   

This article shows how you can increase the admin login session lifetime in Magento 2.

Problem

When you are a developer, it is frustrating to login to admin panel every 15 minutes or 30 minutes. It would be easy to set the admin login session lifetime for a longer period of time so that we don’t have to login continuously.

Cause

By default, the Magento admin login session timeouts in every 900 seconds, i.e. 900/60 = 15 minutes. Hence, you are inactive in Magento admin, then you have to re-login after every 15 minutes.

Solution

1) From Admin Panel

You can increase the admin login session lifetime to a higher value by going to:

STORES > Settings > Configuration > ADVANCED > Admin > Security > Admin Session Lifetime (seconds)

You can set the value in seconds.

3600 = 1 hour
86400 = 1 day (24 hours)
31536000 = 1 year

2) From Command Line

Instead of the admin panel, you can also set the admin session lifetime value from the command line.

Show current set value

bin/magento config:show admin/security/session_lifetime

Set your desired value

bin/magento config:set admin/security/session_lifetime 3600

Check database table

> SELECT * FROM core_config_data WHERE path = 'admin/security/session_lifetime';
+-----------+---------+----------+---------------------------------+----------+---------------------+
| config_id | scope   | scope_id | path                            | value    | updated_at          |
+-----------+---------+----------+---------------------------------+----------+---------------------+
|      6367 | default |        0 | admin/security/session_lifetime | 3600.    | 2021-10-07 22:31:47 |
+-----------+---------+----------+---------------------------------+----------+---------------------+

Hope this helps. Thanks.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to fix the 'too many redirects' error in Magento 2

 Programing Coderfunda     March 30, 2022     Magento, Magento 2     No comments   

 This article presents a technique to the redirect loop error while logging in to the Magento admin panel.


Did installation an existing Magento keep.

Went to the Magento admin login web page

Entered admin username and password

Got the ERR_TOO_MANY_REDIRECTS mistakes


The website has a redirect loop
ERR_TOO_MANY_REDIRECTS

Cause

The problem is with the Cookie Domain for the Magento website.

i.e. the Magento configuration setting for web/cookie/cookie_domain

My Magento website domain was magento.test.
But, in the configuration settings, it was set as magento.host.

Solution

We need to update the configuration settings value for path web/cookie/cookie_domain with the correct cookie-domain name.

There are two ways to update the configuration settings values.

1) Update the configuration setting from the command line

Show the config value:

bin/magento config:show web/cookie/cookie_domain

Set the config value:

bin/magento config:set web/cookie/cookie_domain magento.test

2) Update database table rows

This one seems better as we can see the value for different stores/websites.

Check the values in the database table:

> SELECT * FROM core_config_data WHERE path LIKE '%web/cookie/cookie_domain%';
+-----------+---------+----------+--------------------------+------------------+---------------------+
| config_id | scope   | scope_id | path                     | value            | updated_at          |
+-----------+---------+----------+--------------------------+------------------+---------------------+
|        18 | default |        0 | web/cookie/cookie_domain | magento.host     | 2020-08-26 15:24:07 |
|      1033 | stores  |        3 | web/cookie/cookie_domain | ca.magento.test  | 2020-06-16 16:57:47 |
+-----------+---------+----------+--------------------------+------------------+---------------------+

Update the config setting value:

> UPDATE core_config_data SET value = 'magento.test' WHERE config_id = 18;

Clear Cache

bin/magento cache:flush

Now, you should be able to login to the Magento admin.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Older Posts Home

Meta

Popular Posts

  • Sitaare Zameen Par Full Movie Review
     Here’s a  complete Vue.js tutorial for beginners to master level , structured in a progressive and simple way. It covers all essential topi...
  • Credit card validation in laravel
      Validation rules for credit card using laravel-validation-rules/credit-card package in laravel Install package laravel-validation-rules/cr...
  • C++ in Hindi Introduction
    C ++ का परिचय C ++ एक ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग लैंग्वेज है। C ++ को Bjarne Stroustrup द्वारा विकसित किया गया था। C ++ में आने से पह...
  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • iOS 17 Force Screen Rotation not working on iPAD only
    I have followed all the links on Google and StackOverFlow, unfortunately, I could not find any reliable solution Specifically for iPad devic...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (69)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • July (4)
  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

Loading...

Laravel News

Loading...

Copyright © CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda