You are here

function commerce_license_field_widget_form_alter in Commerce License 8.2

Same name and namespace in other branches
  1. 7 commerce_license.module \commerce_license_field_widget_form_alter()

Implements hook_field_widget_form_alter().

See also

\Drupal\commerce_license\FormAlter\ProductVariationTypeFormAlter::formAlter()

File

./commerce_license.module, line 105
Contains commerce_license.module.

Code

function commerce_license_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['items']
    ->getFieldDefinition();
  $field_name = $field_definition
    ->getName();
  $entity_type_id = $field_definition
    ->getTargetEntityTypeId();
  if ($field_name == 'license_type' && $entity_type_id == 'commerce_product_variation') {

    // If the plugin ID form element doesn't have an '#options' key, then we
    // can't remove the plugins that should not be allowed here, either because
    // the widget for this field has been changed by an admin, or because the
    // code for the commerce_plugin_item field type widgets has been changed.
    // In which case, just crash rather than allowing access to a license type
    // that shouldn't be allowed. License types can escalate a user's privileges
    // on the site, and so granting license that shouldn't be allowed is a
    // security risk.
    if (!isset($element['target_plugin_id']['#options'])) {
      throw new \Exception("Unable to change the plugin type options on the license_type field on the commerce_product_variation. Check the field widget type.");
    }

    // Get the allowed license types for this product variation type.
    $bundle_name = $field_definition
      ->getTargetBundle();
    $product_variation_type = \Drupal::entityTypeManager()
      ->getStorage('commerce_product_variation_type')
      ->load($bundle_name);
    $license_types = $product_variation_type
      ->getThirdPartySetting('commerce_license', 'license_types') ?: [];

    // If there's no license type restrictions defined, we allow all types.
    if ($license_types) {
      $default_value = $element['target_plugin_id']['#default_value'];

      // Ensure we don't remove the default value from the options, in case
      // the product variation references a license type that's no longer
      // "allowed".
      if (!isset($license_types[$default_value])) {
        $license_types[$default_value] = $default_value;
      }

      // Remove plugin IDs from the options array.
      $element['target_plugin_id']['#options'] = array_intersect_key($element['target_plugin_id']['#options'], $license_types);
    }
  }
}