Magento 2 Create Catalog Price Rule Programmatically
-
05-10-2020 - |
Pergunta
I have used the below code to create catalog price rule programmatically. It creates the rule,but the conditions are not saved.
$catalogPriceRule = $this->_objectManager->create('Magento\CatalogRule\Model\Rule');
$catalogPriceRule
->setName('name')
->setDescription('description')
->setIsActive(1)
->setCustomerGroupIds(array(1))
->setWebsiteIds(array(1))
->setFromDate('')
->setToDate('')
->setSimpleAction('by_fixed')
->setDiscountAmount(10)
->setStopRulesProcessing(0);
$conditions = array();
$conditions[1] = array(
'type' => 'catalogrule/rule_condition_combine',
'aggregator' => 'any',
'value' => "1",
'new_child' => ''
);
$i = 1;
$conditions['1--1'] = array(
'type' => 'catalogrule/rule_condition_product_found',
'value' => 1,
'aggregator' => 'all',
'new_child' => '',
);
$conditions['1--1--1'] = array(
'type' => 'catalogrule/rule_condition_product',
'attribute' => 'sku',
'operator' => '==',
'value' => '24-UB02',
);
$catalogPriceRule->setData('conditions',$conditions);
$catalogPriceRule->loadPost($catalogPriceRule->getData());
$catalogPriceRule->save();
$catalogPriceRule->applyAll();
Solução
check below Code.
Reference: \Magento\CatalogRule\Controller\Adminhtml\Promo\Catalog\Save
Before saving rule validate data It's helping for saving Correct value
$model = $objectManager->create('Magento\CatalogRule\Model\Rule');
$model->setName('name')
->setDescription('description')
->setIsActive(1)
->setCustomerGroupIds(array(1))
->setWebsiteIds(array(1))
->setFromDate('')
->setToDate('')
->setSimpleAction('by_fixed')
->setDiscountAmount(10)
->setStopRulesProcessing(0);
$conditions = array();
$conditions["1"] = array
(
"type" => "Magento\CatalogRule\Model\Rule\Condition\Combine",
"aggregator" => "all",
"value" => 1,
"new_child" => ""
);
$conditions["1--1"] = array
(
"type" => "Magento\CatalogRule\Model\Rule\Condition\Product",
"attribute" => "sku",
"operator" => "==",
"value" => "24-UB02"
);
$model->setData('conditions',$conditions);
// Validating rule data before Saving
$validateResult = $model->validateData(new \Magento\Framework\DataObject($model->getData()));
if ($validateResult !== true) {
foreach ($validateResult as $errorMessage) {
echo $errorMessage;
}
return;
}
try {
$model->loadPost($model->getData());
$model->save();
$ruleJob = $objectManager->get('Magento\CatalogRule\Model\Rule\Job');
$ruleJob->applyAll();
echo "rule created";
} catch (Exception $e) {
echo $e->getMessage();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange