Magento 2 – Apply Conditions in the Frontend

conditions-serializedmagento2

I was add a condition action in custom module admin form in magento 2

enter image description here

I used this blog to create a condition action: https://www.mageworx.com/blog/2016/09/magento-2-module-with-conditions-model-fieldset/

Database:

enter image description here

how we can apply those saved condition in the frontend?

Best Answer

Any rule-model could be used this way:

$ruleModel->validate($validationModel);

But your rule model must extend the \Magento\Rule\Model\AbstractModel class and object which you will validate must have desired data (subtotal in your case, so I suppose it will be instance of \Magento\Quote\Model\Quote\Address).

So, an example will be looking like this:

$address = $block->getAddress(); // or $quote->getAddress();
$rules = $block->getRules(); // load all availabel rules from DB
foreach ($rules as $rule) {
    if ($rule->validate($address)) {
        echo __('Pass conditions of the rule %1', $rule->getId());
    } else {
        echo __('Missed rule %1', $rule->getId());
    }
}

The $rule->validate() will call this code:

/**
 * Validate rule conditions to determine if rule can run
 *
 * @param \Magento\Framework\DataObject $object
 * @return bool
 */
public function validate(\Magento\Framework\DataObject $object)
{
    return $this->getConditions()->validate($object);
}
Related Topic