How to get condition and description of cart price rule using ID programmatically, in Magento 2.

有帮助吗?

解决方案

We can use Magento\SalesRule\Model\RuleRepository

/** @var \Magento\SalesRule\Model\RuleRepository $ruleRepository **/

$rule = $this->ruleRepository->getById($ruleId);

$rule->getDescription();
$rule->getCondition();

Remember to inject this class in the constructor.

其他提示

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

    $rule_id = 1;

    $rule=$objectManager->create('Magento\SalesRule\Model\Rule')->load($rule_id); 

    echo $rule->getIsActive(); 

    echo $rule->getDescription();
    //To get conditions
    print_r($rule->getConditionsSerialized());

The correct way is using dependency injection. You can easily load the shipping rules using the CollectionFactory.

use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory;

class SomeClass 
{

    /**
     * @var CollectionFactory
     */
    protected $ruleCollectionFactory;

    /**
     * ProgramCode constructor.
     * @param CollectionFactory $ruleCollectionFactory
     */
    public function __construct(
        CollectionFactory $ruleCollectionFactory
    ) {
        $this->ruleCollectionFactory = $ruleCollectionFactory;
    }

    public function somefunction() {
        $shoppingCartRules = $this->collectionFactory->create();
        <!-- more code... -->
    }

First, you need to inject Magento\SalesRule\Model\RuleRepository class in your constructor to get rule data based on rule id.

After that you can use below code to retrieve various rule properties:

$ruleId = 25;

$ruleData = $this->ruleRepository->getById($ruleId);

// Get Rule Name
$ruleName = $ruleData->getName();

// Get Rule Description
$ruleDescription = $ruleData->getDescription();

// Get Rule From and To date
$ruleFromDate = $ruleData->getFromDate();
$ruleToDate = $ruleData->getToDate();

Likewise, you can retrieve all its properties. However, if you want to get rule conditions then it is little bit tricky. Suppose, if you have set rule conditions in admin as below:

enter image description here

Then, kindly use below code to retrieve above conditions:

$ruleConditions = [];
$conditionData = $ruleData->getActionCondition()->getConditions();
foreach ($conditionData as $ruleKey => $ruleAction) {                
   $ruleConditions[$ruleKey]['attribute'] = $ruleAction->getAttributeName();
   $ruleConditions[$ruleKey]['value'] = $ruleAction->getValue();
}

The expected output of variable $ruleConditions would be as below:

[
  0 => ['attribute' => 'category_ids',
        'value' => '487, 488, 490, 491, 492, 655, 579, 532, 543',
       ],
  1 => ['attribute' => 'quote_item_qty',
        'value' => '5',
       ],
]

I hope this helps to everyone looking for the same concern.

Thanks,

许可以下: CC-BY-SA归因
scroll top