Skip to content

Instantly share code, notes, and snippets.

@magevision
Created March 1, 2019 12:28
Show Gist options
  • Save magevision/7fae1e5ace423b580646f34c9330115b to your computer and use it in GitHub Desktop.
Save magevision/7fae1e5ace423b580646f34c9330115b to your computer and use it in GitHub Desktop.
AddProductCustomOptionProgrammatically
<?php
namespace MageVision\Blog40\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Api\Data\ProductCustomOptionInterface;
use Magento\Catalog\Model\Product\OptionFactory;
class CatalogProductSaveBeforeObserver implements ObserverInterface
{
/**
* @var OptionFactory
*/
protected $productOptionFactory;
/**
* Catalog Product After Save constructor.
* @param OptionFactory $productOptionFactory
*/
public function __construct(
OptionFactory $productOptionFactory
) {
$this->productOptionFactory = $productOptionFactory;
}
/**
* Catalog Product Before Save
*
* @param \Magento\Framework\Event\Observer $observer
* @return void
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$product = $observer->getEvent()->getProduct();
$exist = false;
//check if the custom option exists
foreach ($product->getOptions() as $option) {
if ($option->getGroupByType() == ProductCustomOptionInterface::OPTION_TYPE_FIELD
&& $option->getTitle() == 'Custom Option') {
$exist = true;
}
}
if (!$exist) {
try {
$optionArray = [
'title' => 'Custom Option',
'type' => 'field',
'is_require' => false,
'sort_order' => 1,
'price' => 0,
'price_type' => 'fixed',
'sku' => '',
'max_characters' => 0
];
$option = $this->productOptionFactory->create();
$option->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($optionArray);
$product->addOption($option);
} catch (\Exception $e) {
//throw new CouldNotSaveException(__('Something went wrong while saving option.'));
}
}
}
}
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="catalog_product_save_before">
<observer name="magevision_blog40_add_custom_option" instance="MageVision\Blog40\Observer\CatalogProductSaveBeforeObserver"/>
</event>
</config>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment