Delete Product Custom Option value if it is null in magento 2
-
15-04-2021 - |
Question
I wish to delete the custom options value of a product if it is null without deleting the option.
Please provide me a solution to delete it without affecting the option
Solution
By using below function you can delete the custom options values. Here I compared the value title as NULL and delete the custom options values
$obj = \Magento\Framework\App\ObjectManager::getInstance();
$productId = 2057;
$productRepository = $obj->get('Magento\Catalog\Api\ProductRepositoryInterface');
$this->prodOptionValue = $obj->get('Magento\Catalog\Model\ResourceModel\Product\Option\Value');
$product = $productRepository->getById($productId);
if (!empty($product->getOptions())) {
foreach ($product->getOptions() as $option) {
foreach ($option->getValues() as $value) {
if($value->getTitle() == NULL){
$this->prodOptionValue->deleteValues($value->getOptionTypeId());
}
}
}
}
Note: Instead of using objectManager, try to use the ProductRepositoryInterface,Value (modal) in the constructor
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange