0

Magento 2.4.6

I creates a sales rule, lets say it has ID 123. I am loading it like this for now (yes, I know ObjectManager is bad practice):

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$rule = $objectManager->create('Magento\SalesRule\Model\Rule')->load(123);

Now, how do I get the automatically created coupons in that sales rule?

2 Answers 2

0

If you have a Magento\SalesRule\Model\Rule object, you can simply use the getCoupons method which returns a array of subordinate coupons.

/** @var \Magento\SalesRule\Model\Coupon[] $subordinateCoupons */
$subordinateCoupons = $rule->getCoupons();
0

While using the ObjectManager directly is considered bad practice in Magento, I understand that you're currently using it to load a sales rule with ID 123. Instead, I'll provide you with an alternative method that follows Magento's best practices by using dependency injection.

To load a sales rule with ID 123 using dependency injection, you can follow these steps:

1)Inject the \Magento\SalesRule\Model\RuleFactory class into your constructor or method:

protected $ruleFactory;

public function __construct(
    \Magento\SalesRule\Model\RuleFactory $ruleFactory
) {
    $this->ruleFactory = $ruleFactory;
}

2)Use the $ruleFactory instance to load the sales rule:

$rule = $this->ruleFactory->create()->load(123);

By utilizing dependency injection and the RuleFactory, you can properly instantiate the Rule model without directly using the ObjectManager.

It's important to follow Magento's best practices and rely on dependency injection to ensure modularity and maintainability in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.