Skip to content

Add a new promotion condition to filter by product #698

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 8.x-2.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php

namespace Drupal\commerce_product\Plugin\Commerce\PromotionCondition;

use Drupal\commerce_promotion\Plugin\Commerce\PromotionCondition\PromotionConditionBase;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Provides an 'Order item: product equals' condition.
*
* @CommercePromotionCondition(
* id = "commerce_product_equals",
* label = @Translation("Product equals"),
* target_entity_type = "commerce_order_item",
* )
*/
class ProductEquals extends PromotionConditionBase implements ContainerFactoryPluginInterface {

/**
* The product storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $productStorage;

/**
* Constructs a new ProductEquals object.
*
* @param array $configuration
* The plugin configuration, i.e. an array with configuration values keyed
* by configuration option name. The special key 'context' may be used to
* initialize the defined contexts by setting it to an array of context
* values keyed by context names.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->productStorage = $entity_type_manager->getStorage('commerce_product');
}

/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
);
}

/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'product_id' => NULL,
] + parent::defaultConfiguration();
}

/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);

$product = $this->productStorage->load($this->configuration['product_id']);
$form['product_id'] = [
'#type' => 'entity_autocomplete',
'#title' => $this->t('Product'),
'#default_value' => $product,
'#target_type' => 'commerce_product',
];
return $form;
}

/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValue($form['#parents']);
$this->configuration['product_id'] = $values['product_id'];
parent::submitConfigurationForm($form, $form_state);
}

/**
* {@inheritdoc}
*/
public function evaluate() {
$product_id = $this->configuration['product_id'];
if (empty($product_id)) {
return FALSE;
}

/** @var \Drupal\commerce_product\Entity\ProductInterface $current_product */
$current_product = $this->getTargetEntity()->getPurchasedEntity()->getProduct();

return $current_product->id() == $product_id;
}

/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Compares the purchased product.');
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<?php

namespace Drupal\commerce_product\Plugin\Commerce\PromotionCondition;

use Drupal\commerce_order\Entity\OrderItemInterface;
use Drupal\commerce_promotion\Plugin\Commerce\PromotionCondition\PromotionConditionBase;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\TermInterface;
use Drupal\taxonomy\TermStorage;

/**
* Provides an 'Order: Total amount comparison' condition.
*
* @CommercePromotionCondition(
* id = "commerce_promotion_product_field_equals",
* label = @Translation("Product field equals"),
* target_entity_type = "commerce_order_item",
* )
*/
class ProductFieldEquals extends PromotionConditionBase {

/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'bundle' => NULL,
'field' => NULL,
] + parent::defaultConfiguration();
}

/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form += parent::buildConfigurationForm($form, $form_state);
$ajax_wrapper_id = Html::getUniqueId('ajax-wrapper');
// Prefix and suffix used for Ajax replacement.
$form['#prefix'] = '<div id="' . $ajax_wrapper_id . '">';
$form['#suffix'] = '</div>';

$selected_bundle = isset($this->configuration['bundle']) ? $this->configuration['bundle'] : NULL;
$bundles = \Drupal::service("entity_type.bundle.info")->getBundleInfo('commerce_product');
$bundle_options = [];
foreach ($bundles as $bundle => $label) {
$bundle_options[$bundle] = $label['label'];
}

$form['bundle'] = [
'#type' => 'select',
'#options' => $bundle_options,
'#title' => t('Product bundle'),
'#default_value' => $selected_bundle,
'#required' => TRUE,
'#ajax' => [
'callback' => [$this, 'bundleAjaxCallback'],
'wrapper' => $ajax_wrapper_id,
],
];
if (!$selected_bundle) {
return $form;
}

$fields = \Drupal::service("entity_field.manager")->getFieldDefinitions('commerce_product', $selected_bundle);
$selected_field = isset($this->configuration['field']) ? $this->configuration['field'] : NULL;

$filed_options = [];
foreach ($fields as $field_id => $field_definition) {
$filed_options[$field_id] = $field_definition->getLabel();
}

$form['field'] = [
'#type' => 'select',
'#title' => t('Field'),
'#options' => $filed_options,
'#default_value' => $selected_field,
'#required' => TRUE,
'#ajax' => [
'callback' => [$this, 'bundleAjaxCallback'],
'wrapper' => $ajax_wrapper_id,
],
];

if (!$selected_field) {
return $form;
}

//Create an empty representative entity
$commerce_product = \Drupal::service('entity_type.manager')->getStorage('commerce_product')->create(array(
'type' => $selected_bundle,
$selected_field => $this->configuration[$selected_field],
)
);

//Get the EntityFormDisplay (i.e. the default Form Display) of this content type
$entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')
->load('commerce_product.' . $selected_bundle . '.default');

//Get the body field widget and add it to the form
if ($widget = $entity_form_display->getRenderer($selected_field)) { //Returns the widget class
$items = $commerce_product->get($selected_field); //Returns the FieldItemsList interface
$items->filterEmptyItems();
$form[$selected_field] = $widget->form($items, $form, $form_state); //Builds the widget form and attach it to your form
$form[$selected_field]['widget']['#required'] = TRUE;
}

return $form;
}


public function bundleAjaxCallback(array $form, FormStateInterface $form_state) {
$triggering_element = $form_state->getTriggeringElement();
$parents = array_slice($triggering_element['#array_parents'], 0, -1);
$form_element = NestedArray::getValue($form, $parents);
return $form_element;
}

/**
* {@inheritdoc}
*/
public function evaluate() {
$bundle_id = $this->configuration['bundle'];
if (empty($bundle_id)) {
return FALSE;
}
$field_id = $this->configuration['field'];
if (empty($field_id)) {
return FALSE;
}
/** @var OrderItemInterface $order_item */
$order_item = $this->getContextValue('commerce_order_item');

/** @var \Drupal\commerce_product\Entity\ProductInterface $current_product */
$current_product = $order_item->getPurchasedEntity()->getProduct();
if ($current_product->bundle() != $bundle_id) {
return FALSE;
}

if (!$current_product->hasField($field_id)) {
return FALSE;
}

$field_type = $current_product->get($field_id)->getFieldDefinition()->getType();
$target_type = NULL;
if ($field_type == 'entity_reference') {
$target_type = $current_product->get($field_id)->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
}

if ($target_type == 'taxonomy_term') {
if ($current_product->get($field_id)->getValue() == $this->configuration[$field_id]) {
return TRUE;
}
else {
/** @var TermInterface $term */
$term = \Drupal::service('entity_type.manager')
->getStorage("taxonomy_term")->load($this->configuration[$field_id][0]['target_id']);
$tree = \Drupal::service('entity_type.manager')
->getStorage("taxonomy_term")
->loadTree($term->getVocabularyId(), $term->id());
$found = FALSE;
foreach ($tree as $item) {
if ($item->tid == $current_product->get($field_id)->getValue()[0]['target_id']) {
$found = TRUE;
break;
}
}
return $found;
}
}
elseif ($current_product->get($field_id)->getValue() != $this->configuration[$field_id]) {
return FALSE;
}

return TRUE;
}

/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Compares the product entity.');
}

}
Loading