I'm using Magento 2.2.5 and tried to implement a new cart price rule. I followed two very helpfull tutorials for that:
https://magently.com/blog/magento-2-custom-sales-rule-condition/
https://www.youtube.com/watch?v=yMw3W6XwUl4
both are working fine with some changes, but I'm now trying to get access to the cart or more specific to the items in the cart in the validation function and this does not work as expected. Do somebody have an idea how i could access the items in the active cart within the custom rule?
<?php
namespace ...;
/**
* Class Customer
*/
class Customer extends \Magento\Rule\Model\Condition\AbstractCondition
{
/**
* @var \Magento\Config\Model\Config\Source\Yesno
*/
protected $sourceYesno;
/**
* @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory
*/
protected $orderFactory;
/**
* @var \Magento\Checkout\Model\Cart
*/
protected $cart;
/**
* Constructor
* @param \Magento\Rule\Model\Condition\Context $context
* @param \Magento\Config\Model\Config\Source\Yesno $sourceYesno
* @param \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory
* @param array $data
*/
public function __construct(
\Magento\Rule\Model\Condition\Context $context,
\Magento\Config\Model\Config\Source\Yesno $sourceYesno,
\Magento\Checkout\Model\Cart $cart,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderFactory,
array $data = []
) {
parent::__construct($context, $data);
$this->sourceYesno = $sourceYesno;
$this->orderFactory = $orderFactory;
$this->cart = $cart;
}
/**
* Load attribute options
* @return $this
*/
public function loadAttributeOptions()
{
$this->setAttributeOption([
'customer_first_order' => __('Customer first order')
]);
return $this;
}
/**
* Get input type
* @return string
*/
public function getInputType()
{
return 'select';
}
/**
* Get value element type
* @return string
*/
public function getValueElementType()
{
return 'select';
}
/**
* Get value select options
* @return array|mixed
*/
public function getValueSelectOptions()
{
if (!$this->hasData('value_select_options')) {
$this->setData(
'value_select_options',
$this->sourceYesno->toOptionArray()
);
}
return $this->getData('value_select_options');
}
/**
* Validate Customer First Order Rule Condition
* @param \Magento\Framework\Model\AbstractModel $model
* @return bool
*/
public function validate(\Magento\Framework\Model\AbstractModel $model)
{
$price = 0;
$items = $cart->getQuote()->getAllItems();
foreach($items as $item) {
if($item->getSku != "10624"){
$price = $price + $item->getPrice();
}
}
if($price > 50){
return true;
}else{
return false;
}
}
}