At times during the development phase of a Magento 2 site, you might want to add a virtual product – as either a client requirement or an ad-hoc request. Creating a virtual product can be done in two ways:
- From the Magento 2 backend as the administrator and
- Programmatically (manually) from the front end.
In this article, we will walk you through the procedure and purpose of creating a virtual product, programmatically.
Straight ahead, below is the code which injects our necessary dependencies to the __construct function.
In order to access a Magento project object, it’s necessary to inject interface functions to the already defined __construct function. The interface functions associated are \Magento\Catalog\Api\Data\ProductInterfaceFactory and \Magento\Catalog\Api\ProductRepositoryInterface.
Moving on, below is the code to create a virtual product using the injected interface functions:
Now, let’s understand the purpose of codes implemented:
- $this->productFactory->create() creates the product object. Once the object is created, properties of the product such as SKU, name, and description will be set.
- $product->setWebsiteIds() assigns the product to one website and if there are multiple websites for which the same product is to be assigned, then you could call the website IDs through the store.
- $product->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL) sets product as a virtual product, while TYPE_SIMPLE creates the product as a simple product.
- $product->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH) sets product visibility as both catalog and search. VISIBILITY_IN_CATALOG sets product visibility as a catalog, VISIBILITY_IN_SEARCH sets product visibility as search, and VISIBILITY_NOT_VISIBLE makes the product not visible individually.
- $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED) makes the product enabled and “STATUS_DISABLED” makes the product disabled.
- To add the image to the product, we have used the code “$product->addImageToMediaGallery($imagePath, [‘image’, ‘small_image’, ‘thumbnail’], false, false);”. Here in the $imagePath, we need to specify the entire path of the image file.
Apart from the default attributes of the product, we can also save the custom attributes of the products by using their attribute code. For example, if I have a text attribute called “created_by” and wish to save this attribute to the product, I can save the attribute using this code $product->setCreatedBy(‘Created By’).
If you have any queries regarding the procedure/code or you are in need of any technical assistance regarding your store setup, we’re just a click away. Feel free to drop us a line and we could help you and ease up your process of creating better Magento sites.