I tried to add custom option to a product into an observer on catalog_product_save_after
event.
I am already successful add custom option for the simple product with this script:
class Productsaveafter implements ObserverInterface
{
protected $ObjectManager;
protected $product;
public function __construct(
\Magento\Framework\ObjectManagerInterface $ObjectManager,
\Magento\Catalog\Model\Product $product
){
$this->_objectManager = $ObjectManager;
$this->_product = $product;
}
public function execute(
\Magento\Framework\Event\Observer $observer
)
{
$_product = $observer->getProduct();
$productId = $_product->getId();
$personalisatie = $_product->getData('personalisatie_toevoegen');
if(!$_product->getHasOptions() && $personalisatie==1 ){
try{
$customOption = $this->_objectManager->create('Magento\Catalog\Api\Data\ProductCustomOptionInterface');
$var = NULL;
$customOption
->setOptionId($var)
->setProductId($productId)
->setType('field')
->setIsRequire("0")
->setSku("")
->setMaxCharacters("13")
->setFileExtension("")
->setImageSizeX("0")
->setImageSizeY("0")
->setSortOrder("1")
->setDefaultTitle("Naam")
->setStoreTitle("Naam")
->setTitle("Naam")
->setDefaultPrice("0.00")
->setDefaultPriceType("fixed")
->setStorePrice("0.00")
->setStorePriceType("0.00")
->setPrice("10")
->setPriceType('fixed')
->setRecordId("0")
->setProductSku($_product->getSku());
$customOptions[] = $customOption;
$_product->setOptions($customOptions)->save();
} catch (\Exception $e) {
var_dump($e->getMessage());
}
}
}
}
But for the configurable product is not working at all.
What i see is that !$_product->getHasOptions() is not true. so the code is not executed for configurable product.
If I remove !$_product->getHasOptions()
form if statement when i press save of the produc my backend page is loading for few minutes then and page is blocked and the custom options is not added.
Is there another way to add custom option for the configurable products?
Best Answer
You need to use
Magento\Catalog\Api\ProductCustomOptionRepositoryInterface::save
method to save custom options.Replace
with
where optionRepository is
Magento\Catalog\Api\ProductCustomOptionRepositoryInterface
instance