You are here

uc_attribute.module in Ubercart 8.4

Ubercart Attribute module.

Allows customers to buy slightly different products from the same listing.

Many manufacturers provide options to their products. This module provides a way for store administrators to consolidate these options into one product instead of listing each combination separately.

File

uc_attribute/uc_attribute.module
View source
<?php

/**
 * @file
 * Ubercart Attribute module.
 *
 * Allows customers to buy slightly different products from the same listing.
 *
 * Many manufacturers provide options to their products. This module provides
 * a way for store administrators to consolidate these options into one product
 * instead of listing each combination separately.
 */
use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\PrependCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Database\Query\Condition;
use Drupal\Core\Database\Query\Merge;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\uc_cart\CartItemInterface;
use Drupal\uc_order\OrderInterface;
use Drupal\uc_order\OrderProductInterface;

/**
 * Implements hook_help().
 */
function uc_attribute_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {

    // Help messages for the attributes overview on products and classes.
    case 'uc_attribute.product_attributes':
      return '<p>' . t('Add attributes to this product using the <a href=":url">add attributes form</a>. You may then adjust the settings for these attributes on this page and go on to configure their options in the <em>Options</em> tab.', [
        ':url' => Url::fromRoute('uc_attribute.product_attributes_add', [
          'node' => $route_match
            ->getRawParameter('node'),
        ])
          ->toString(),
      ]) . '</p>';
    case 'uc_attribute.product_class_attributes':
      return '<p>' . t('Add attributes to the product class using the <a href=":url">add attributes form</a>. You may then adjust the settings for these attributes on this page and go on to configure their options in the <em>Options</em> tab.', [
        ':url' => Url::fromRoute('uc_attribute.product_class_attributes_add', [
          'node_type' => $route_match
            ->getRawParameter('node_type'),
        ])
          ->toString(),
      ]) . '</p>';

    // Help message for adding an attribute to a product or class.
    case 'uc_attribute.product_attributes_add':
    case 'uc_attribute.product_class_attributes_add':
      return '<p>' . t('Select the attributes you want to add and submit the form.') . '</p>';

    // Help message for adjusting the options on a product or class.
    case 'uc_attribute.product_options':
    case 'uc_attribute.product_class_options':
      return '<p>' . t('Use the checkboxes to enable options for attributes and the radio buttons to specify the default option. Attributes with no enabled options will be displayed as text fields. Drag and drop the options to reorder them.') . '</p><p>' . t('The cost, price and weight fields will make adjustments against the original product, so you may enter positive or negative amounts here, or enter 0 if the option should make no adjustment.') . '</p>';

    // Help message for the product Adjustments tab.
    case 'uc_attribute.product_adjustments':
      return '<p>' . t('Enter an alternate SKU to be used when the specified set of options are chosen and the product is added to the cart.') . '</p><p>' . t('<b>Warning:</b> Adding or removing attributes from this product will reset all the SKUs on this page to the default product SKU.') . '</p>';
  }
}

/**
 * Implements hook_theme().
 */
function uc_attribute_theme() {
  return [
    'uc_attribute_option' => [
      'variables' => [
        'option' => '',
        'price' => '',
      ],
      'template' => 'uc-attribute-option',
    ],
    'uc_product_attributes' => [
      'render element' => 'attributes',
      'file' => 'uc_attribute.theme.inc',
      'function' => 'theme_uc_product_attributes',
    ],
  ];
}

/**
 * Implements hook_form_FORM_ID_alter() for uc_product_settings_form().
 */
function uc_attribute_form_uc_product_settings_form_alter(&$form, FormStateInterface $form_state) {
  $form['attributes'] = [
    '#type' => 'details',
    '#title' => 'Attribute settings',
    '#group' => 'product-settings',
    '#weight' => -3,
  ];
  $form['attributes']['uc_attribute_option_price_format'] = [
    '#type' => 'radios',
    '#title' => t('Option price format'),
    '#default_value' => \Drupal::config('uc_attribute.settings')
      ->get('option_price_format'),
    '#options' => [
      'none' => t('Do not display'),
      'adjustment' => t('Display price adjustment'),
      'total' => t('Display total price'),
    ],
    '#description' => t('Determines how price variations are displayed to the customer. Prices may be displayed directly next to each attribute option in the attribute selection form either as a total price for the product with that option or as an adjustment (+ or -) showing how that option affects the product base price. Note that the price will always be displayed as an adjustment for attributes that can have multiple options (using checkboxes).'),
  ];
  $form['#submit'][] = 'uc_attribute_uc_product_settings_form_submit';
}

/**
 * Submit handler for product attribute settings.
 *
 * @see uc_attribute_form_uc_product_settings_form_alter()
 */
function uc_attribute_uc_product_settings_form_submit($form, FormStateInterface $form_state) {
  \Drupal::configFactory()
    ->getEditable('uc_attribute.settings')
    ->set('option_price_format', $form_state
    ->getValue('uc_attribute_option_price_format'))
    ->save();

  // Clear node entity cache, to force re-rendering of attribute forms.
  \Drupal::entityTypeManager()
    ->getViewBuilder('node')
    ->resetCache();
}

/**
 * Implements hook_module_implements_alter().
 *
 * Ensures that attribute form changes are made after (e.g.) product kits.
 */
function uc_attribute_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'uc_form_alter') {
    $group = $implementations['uc_attribute'];
    unset($implementations['uc_attribute']);
    $implementations['uc_attribute'] = $group;
  }
}

/**
 * Implements hook_uc_form_alter().
 *
 * Attaches option selectors to the form with the "Add to Cart" button.
 *
 * This function also handles selecting attributes for products added to orders
 * manually.
 */
function uc_attribute_uc_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (strpos($form_id, 'add_to_cart_form') || $form_id == 'uc_order_add_product_form') {
    $use_ajax = strpos($form_id, 'add_to_cart_form') && \Drupal::config('uc_product.settings')
      ->get('update_node_view');
    $node =& $form['node']['#value'];
    $id = $form_id . '-' . $node
      ->id() . '-attributes';

    // If the node has a product list, add attributes to them.
    if (isset($form['products']) || isset($form['sub_products'])) {
      if (isset($form['products'])) {
        $element =& $form['products'];
      }
      else {
        $element =& $form['sub_products'];
      }
      foreach (Element::children($element) as $key) {
        $element[$key]['attributes'] = _uc_attribute_alter_form($id . '-' . $key, $node->products[$key], $use_ajax);
        if (is_array($element[$key]['attributes'])) {
          $element[$key]['attributes']['#tree'] = TRUE;
          $element[$key]['#type'] = 'details';
        }
      }
    }
    else {
      $form['attributes'] = _uc_attribute_alter_form($id, $node, $use_ajax);
      if (is_array($form['attributes'])) {
        $form['attributes']['#tree'] = TRUE;
        $form['attributes']['#weight'] = -1;
      }
    }
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter() for uc_product_buy_it_now_form().
 */
function uc_attribute_form_uc_product_buy_it_now_form_alter(&$form, FormStateInterface $form_state) {
  $form['#validate'][] = 'uc_attribute_buy_it_now_form_validate';
}

/**
 * Validation callback for "buy it now" forms with attributes.
 */
function uc_attribute_buy_it_now_form_validate(&$form, FormStateInterface $form_state) {
  $attributes = uc_product_get_attributes($form_state
    ->getValue('nid'));
  if (!empty($attributes)) {
    \Drupal::messenger()
      ->addError(t('This product has options that need to be selected before purchase. Please select them in the form below.'));
    $form_state
      ->setRedirect('entity.node.canonical', [
      'node' => $form_state
        ->getValue('nid'),
    ]);

    // Prevent submit handlers from running.
    $form_state
      ->setSubmitHandlers([]);
  }
}

/**
 * Implements hook_node_load().
 */
function uc_attribute_node_load($nodes) {
  foreach ($nodes as $node) {
    if (uc_product_is_product($node)) {
      $node->attributes = uc_product_get_attributes($node
        ->id());
    }
  }
}

/**
 * Implements hook_node_insert().
 */
function uc_attribute_node_insert($node) {

  // Set attributes from class attributes.
  $connection = \Drupal::database();
  $select = $connection
    ->select('uc_class_attributes', 'ca')
    ->fields('ca', [
    'aid',
    'label',
    'ordering',
    'required',
    'display',
    'default_option',
  ])
    ->condition('pcid', $node
    ->getType());

  // SELECT $node->nid AS nid.
  $select
    ->addExpression(':nid', 'nid', [
    ':nid' => $node
      ->id(),
  ]);
  $connection
    ->insert('uc_product_attributes')
    ->from($select)
    ->execute();

  // Set options from class options.
  $select = $connection
    ->select('uc_class_attribute_options', 'co')
    ->fields('co', [
    'oid',
    'cost',
    'price',
    'weight',
    'ordering',
  ])
    ->condition('pcid', $node
    ->getType());
  $select
    ->addExpression(':nid', 'nid', [
    ':nid' => $node
      ->id(),
  ]);
  $connection
    ->insert('uc_product_options')
    ->from($select)
    ->execute();
}

/**
 * Implements hook_node_delete().
 */
function uc_attribute_node_delete($node) {
  $connection = \Drupal::database();
  $connection
    ->delete('uc_product_options')
    ->condition('nid', $node
    ->id())
    ->execute();
  $connection
    ->delete('uc_product_adjustments')
    ->condition('nid', $node
    ->id())
    ->execute();
  $connection
    ->delete('uc_product_attributes')
    ->condition('nid', $node
    ->id())
    ->execute();
}

/**
 * Implements hook_node_update_index().
 */
function uc_attribute_node_update_index($node) {
  $output = '';
  $attributes = uc_product_get_attributes($node
    ->id());
  foreach ($attributes as $attribute) {
    $output .= '<h3>' . _uc_attribute_get_name($attribute) . '</h3>';
    foreach ($attribute->options as $option) {
      $output .= $option->name . ' ';
    }
    $output .= "\n";
  }
  $connection = \Drupal::database();
  $result = $connection
    ->query("SELECT model FROM {uc_product_adjustments} WHERE nid = :nid", [
    ':nid' => $node
      ->id(),
  ]);
  while ($model = $result
    ->fetchField()) {
    $output .= '<h2>' . $model . "</h2>\n";
  }
  return $output;
}

/**
 * Implements hook_uc_product_models().
 *
 * @param int $nid
 *   Node number for product type node.
 *
 * @return array
 *   Array of SKUs (model numbers) for this $nid.
 */
function uc_attribute_uc_product_models($nid) {

  // Get all the SKUs for all the attributes on this node.
  $connection = \Drupal::database();
  $models = $connection
    ->query("SELECT DISTINCT model FROM {uc_product_adjustments} WHERE nid = :nid", [
    ':nid' => $nid,
  ])
    ->fetchCol();
  return $models;
}

/**
 * Implements hook_uc_add_to_cart_data().
 *
 * Stores the customer's choices in the cart.
 */
function uc_attribute_uc_add_to_cart_data($form_values) {
  if (isset($form_values['attributes'])) {
    return [
      'attributes' => $form_values['attributes'],
    ];
  }
  else {
    return [
      'attributes' => [],
    ];
  }
}

/**
 * Implements hook_uc_order_product_alter().
 */
function uc_attribute_uc_order_product_alter(OrderProductInterface &$product, OrderInterface $order) {

  // Convert the attribute and option ids to their current names. This
  // preserves the important data in case the attributes or options are
  // changed later.
  if (!empty($product->data->attributes)) {
    $attributes_keys = array_keys($product->data->attributes);
    if (is_numeric(array_shift($attributes_keys))) {
      $attributes = [];
      $options = _uc_cart_product_get_options($product);
      foreach ($options as $option) {
        $attributes[$option['attribute']][$option['oid']] = $option['name'];
      }
      $product->data->attributes = $attributes;
    }
  }
}

/**
 * Implements hook_node_type_delete().
 */
function uc_attribute_node_type_delete(NodeTypeInterface $type) {
  $connection = \Drupal::database();
  $connection
    ->delete('uc_class_attributes')
    ->condition('pcid', $type
    ->id())
    ->execute();
  $connection
    ->delete('uc_class_attribute_options')
    ->condition('pcid', $type
    ->id())
    ->execute();
}

/**
 * Implements hook_uc_product_alter().
 */
function uc_attribute_uc_product_alter(&$node) {
  if (isset($node->data['attributes']) && is_array($node->data['attributes'])) {
    $options = _uc_cart_product_get_options($node);
    foreach ($options as $option) {
      $node->cost->value += $option['cost'];
      $node->price->value += $option['price'];
      $node->display_price += $option['price'];
      $node->weight->value += $option['weight'];
    }
    $combination = [];
    foreach ($node->data['attributes'] as $aid => $value) {
      if (is_numeric($value)) {
        $attribute = uc_attribute_load($aid, $node
          ->id(), 'product');
        if ($attribute && ($attribute->display == 1 || $attribute->display == 2)) {
          $combination[$aid] = $value;
        }
      }
    }
    ksort($combination);
    $connection = \Drupal::database();
    $model = $connection
      ->query("SELECT model FROM {uc_product_adjustments} WHERE nid = :nid AND combination LIKE :combo", [
      ':nid' => $node
        ->id(),
      ':combo' => serialize($combination),
    ])
      ->fetchField();
    if (!empty($model)) {
      $node->model = $model;
    }
  }
}

/**
 * Implements hook_uc_product_description().
 */
function uc_attribute_uc_product_description($product) {
  $description = [
    'attributes' => [
      '#product' => [
        '#type' => 'value',
        '#value' => $product,
      ],
      '#theme' => 'uc_product_attributes',
      '#weight' => 1,
    ],
  ];
  $desc =& $description['attributes'];

  // Cart version of the product has numeric attribute => option values so we
  // need to retrieve the right ones.
  $weight = 0;
  if ($product instanceof CartItemInterface) {
    foreach (_uc_cart_product_get_options($product) as $option) {
      if (!isset($desc[$option['aid']])) {
        $desc[$option['aid']]['#attribute_name'] = $option['attribute'];
        $desc[$option['aid']]['#options'] = [
          $option['name'],
        ];
      }
      else {
        $desc[$option['aid']]['#options'][] = $option['name'];
      }
      $desc[$option['aid']]['#weight'] = $weight++;
    }
  }
  elseif (!empty($product->data->attributes)) {
    foreach ($product->data->attributes as $attribute => $option) {
      $desc[] = [
        '#attribute_name' => $attribute,
        '#options' => $option,
        '#weight' => $weight++,
      ];
    }
  }
  return $description;
}

/**
 * Loads attribute objects from the database.
 *
 * @todo If we feel it necessary, we could optimize this, by inverting the
 * logic; that is, we could make uc_attribute load call this function and allow
 * this function to minimize the number of queries necessary. -cha0s
 *
 * @param array $aids
 *   Attribute IDs to load.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param int $id
 *   The ID of the product/class this attribute belongs to.
 *
 * @return array
 *   An array of loaded attributes.
 */
function uc_attribute_load_multiple(array $aids = [], $type = '', $id = NULL) {
  $sql = uc_attribute_type_info($type);

  // Product/class attributes.
  $connection = \Drupal::database();
  if (!empty($type)) {

    // Seems like a big query to get attribute IDs, but it's all about the sort.
    // (I'm not sure if the default ordering is propagating down correctly here.
    // It appears that product/class attributes with no ordering won't let the
    // attribute's propagate down, as it does when loading. -cha0s)
    $query = $connection
      ->select($sql['attr_table'], 'uca')
      ->fields('uca', [
      'aid',
    ])
      ->condition("uca.{$sql['id']}", $id);
    $query
      ->leftJoin('uc_attributes', 'ua', 'uca.aid = ua.aid');
    $query
      ->orderBy('uca.ordering')
      ->orderBy('ua.name');
  }
  else {
    $query = $connection
      ->select('uc_attributes', 'ua')
      ->fields('ua', [
      'aid',
    ])
      ->orderBy('ordering')
      ->orderBy('name');
  }

  // Filter by the attribute IDs requested.
  if (!empty($aids)) {

    // Sanity check - filter out non-numeric attribute IDs.
    $aids = array_filter($aids, 'is_numeric');
    $query
      ->condition('ua.aid', $aids, 'IN');
  }
  $aids = $query
    ->execute()
    ->fetchCol();

  // Load the attributes.
  $attributes = [];
  foreach ($aids as $aid) {
    $attributes[$aid] = uc_attribute_load($aid, $id, $type);
  }
  return $attributes;
}

/**
 * Loads an attribute from the database.
 *
 * @param int $aid
 *   The ID of the attribute.
 * @param int $id
 *   The ID of the product/class this attribute belongs to.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 *
 * @return object|false
 *   The attribute object, or FALSE if it doesn't exist.
 */
function uc_attribute_load($aid, $id = NULL, $type = '') {
  $sql = uc_attribute_type_info($type);
  $connection = \Drupal::database();
  switch ($type) {
    case 'product':
    case 'class':

      // Read attribute data.
      $query = $connection
        ->select('uc_attributes', 'a')
        ->fields('a', [
        'aid',
        'name',
        'description',
      ])
        ->condition('a.aid', $aid);
      $query
        ->leftJoin($sql['attr_table'], 'pa', "a.aid = pa.aid AND pa.{$sql['id']} = :id", [
        ':id' => $id,
      ]);
      $query
        ->fields('pa', [
        'label',
        'default_option',
        'required',
        'ordering',
        'display',
        $sql['id'],
      ]);
      $query
        ->addField('a', 'label', 'default_label');
      $query
        ->addField('a', 'ordering', 'default_ordering');
      $query
        ->addField('a', 'required', 'default_required');
      $query
        ->addField('a', 'display', 'default_display');
      $attribute = $query
        ->execute()
        ->fetchObject();

      // Don't try to build it further if it failed already.
      if (!$attribute) {
        return FALSE;
      }

      // Set any missing defaults.
      foreach ([
        'ordering',
        'required',
        'display',
        'label',
      ] as $field) {
        if (isset($attribute->{"default_{$field}"}) && is_null($attribute->{$field})) {
          $attribute->{$field} = $attribute->{"default_{$field}"};
        }
      }
      if (empty($attribute->label)) {
        $attribute->label = $attribute->name;
      }

      // Read option data.
      $query = $connection
        ->select($sql['opt_table'], 'po')
        ->fields('po', [
        $sql['id'],
        'oid',
        'cost',
        'price',
        'weight',
        'ordering',
      ]);
      $query
        ->leftJoin('uc_attribute_options', 'ao', "po.oid = ao.oid AND po.{$sql['id']} = :id", [
        ':id' => $id,
      ]);
      $query
        ->fields('ao', [
        'name',
        'aid',
      ])
        ->condition('aid', $aid)
        ->orderBy('po.ordering')
        ->orderBy('ao.name');
      $result = $query
        ->execute();
      break;
    default:

      // Read attribute and option data.
      $attribute = $connection
        ->query("SELECT * FROM {uc_attributes} WHERE aid = :aid", [
        ':aid' => $aid,
      ])
        ->fetchObject();
      $result = $connection
        ->query("SELECT * FROM {uc_attribute_options} WHERE aid = :aid ORDER BY ordering, name", [
        ':aid' => $aid,
      ]);

      // Don't try to build it further if it failed already.
      if (!$attribute) {
        return FALSE;
      }
      break;
  }

  // Got an attribute?
  if ($attribute) {

    // Get its options, too.
    $attribute->options = [];
    foreach ($result as $option) {
      $attribute->options[$option->oid] = $option;
    }
  }
  return $attribute;
}

/**
 * Fetches an array of attribute objects that belong to a product.
 *
 * @param int $nid
 *   Product node id whose attributes to load.
 *
 * @return object[]
 *   The array of attribute objects.
 */
function uc_attribute_load_product_attributes($nid) {
  return uc_attribute_load_multiple([], 'product', $nid);
}

/**
 * Saves an attribute object to the database.
 *
 * @param object $attribute
 *   The attribute object to save.
 *
 * @return \Drupal\Core\Database\StatementInterface|null
 *   A prepared statement, or NULL if the query is not valid.
 */
function uc_attribute_save(&$attribute) {
  $fields = [
    'name' => $attribute->name,
    'label' => $attribute->label,
    'ordering' => $attribute->ordering,
    'required' => (int) $attribute->required,
    'display' => $attribute->display,
    'description' => $attribute->description,
  ];
  $connection = \Drupal::database();
  if (empty($attribute->aid)) {
    $attribute->aid = $connection
      ->insert('uc_attributes')
      ->fields($fields)
      ->execute();
    return Merge::STATUS_INSERT;
  }
  else {
    return $connection
      ->merge('uc_attributes')
      ->key('aid', $attribute->aid)
      ->fields($fields)
      ->execute();
  }
}

/**
 * Deletes an attribute from the database.
 *
 * @param int $aid
 *   Attribute ID to delete.
 *
 * @return int
 *   The Drupal SAVED_DELETED flag.
 */
function uc_attribute_delete($aid) {

  // Delete the class attributes and their options.
  uc_attribute_subject_delete($aid, 'class');

  // Delete the product attributes and their options.
  uc_attribute_subject_delete($aid, 'product');

  // Delete base attributes and their options.
  $connection = \Drupal::database();
  $connection
    ->delete('uc_attribute_options')
    ->condition('aid', $aid)
    ->execute();
  $connection
    ->delete('uc_attributes')
    ->condition('aid', $aid)
    ->execute();
  return SAVED_DELETED;
}

/**
 * Loads an attribute option from the database.
 *
 * @param int $oid
 *   Option ID to load.
 *
 * @return object
 *   The attribute option object.
 */
function uc_attribute_option_load($oid) {
  $connection = \Drupal::database();
  return $connection
    ->query("SELECT * FROM {uc_attribute_options} WHERE oid = :oid", [
    ':oid' => $oid,
  ])
    ->fetchObject();
}

/**
 * Saves an attribute object to the database.
 *
 * @param object $option
 *   The attribute option object to save.
 *
 * @return \Drupal\Core\Database\StatementInterface|null
 *   A prepared statement, or NULL if the query is not valid.
 */
function uc_attribute_option_save(&$option) {
  $fields = [
    'aid' => $option->aid,
    'name' => $option->name,
    'cost' => $option->cost,
    'price' => $option->price,
    'weight' => $option->weight,
    'ordering' => $option->ordering,
  ];
  $connection = \Drupal::database();
  if (empty($option->oid)) {
    $option->oid = $connection
      ->insert('uc_attribute_options')
      ->fields($fields)
      ->execute();
    return Merge::STATUS_INSERT;
  }
  else {
    return $connection
      ->merge('uc_attribute_options')
      ->key('oid', $option->oid)
      ->fields($fields)
      ->execute();
  }
}

/**
 * Deletes an attribute option from the database.
 *
 * @param int $oid
 *   Option ID to delete.
 *
 * @return int
 *   The Drupal SAVED_DELETED flag.
 */
function uc_attribute_option_delete($oid) {

  // Delete the class attribute options.
  uc_attribute_subject_option_delete($oid, 'class');

  // Delete the product attribute options (and the adjustments!).
  uc_attribute_subject_option_delete($oid, 'product');

  // Delete base attributes and their options.
  $connection = \Drupal::database();
  $connection
    ->delete('uc_attribute_options')
    ->condition('oid', $oid)
    ->execute();
  return SAVED_DELETED;
}

/**
 * Saves a product/class attribute.
 *
 * @param &$attribute
 *   The product/class attribute.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param string $id
 *   The product/class ID.
 * @param bool $save_options
 *   Save the product/class attribute's options, too?
 *
 * @return \Drupal\Core\Database\StatementInterface|null
 *   A prepared statement, or NULL if the query is not valid.
 */
function uc_attribute_subject_save(&$attribute, $type, $id, $save_options = FALSE) {
  $sql = uc_attribute_type_info($type);

  // First, save the options. First because if this is an insert, we'll set
  // a default option for the product/class attribute.
  if ($save_options && is_array($attribute->options)) {
    foreach ($attribute->options as $option) {

      // Sanity check!
      $option = (object) $option;
      uc_attribute_subject_option_save($option, $type, $id);
    }

    // Is this an insert? If so, we'll set the default option.
    if (!uc_attribute_subject_exists($attribute->aid, $type, $id)) {
      $default_option = 0;

      // Make the first option (if any) the default.
      if (!empty($attribute->options) && is_array($attribute->options)) {
        $option = (object) reset($attribute->options);
        $default_option = $option->oid;
      }
      $attribute->default_option = $default_option;
    }
  }

  // Ensure the attribute's ID property is set.
  $attribute->{$sql['id']} = $id;
  $connection = \Drupal::database();
  return $connection
    ->merge($sql['attr_table'])
    ->keys([
    $sql['id'] => $id,
    'aid' => $attribute->aid,
  ])
    ->fields([
    'label' => $attribute->label,
    'ordering' => $attribute->ordering,
    'default_option' => isset($attribute->default_option) ? $attribute->default_option : 0,
    'required' => (int) $attribute->required,
    'display' => $attribute->display,
  ])
    ->execute();
}

/**
 * Deletes an attribute and all options associated with it.
 *
 * @param int $aid
 *   The base attribute ID.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param int $id
 *   The product/class ID.
 *
 * @return int
 *   The Drupal SAVED_DELETED flag.
 */
function uc_attribute_subject_delete($aid, $type, $id = NULL) {
  $sql = uc_attribute_type_info($type);
  $connection = \Drupal::database();
  $query = $connection
    ->select('uc_attribute_options', 'a')
    ->fields('a', [
    'oid',
  ]);
  $query
    ->join($sql['opt_table'], 'subject', 'a.oid = subject.oid');

  // Base conditions, and an ID check if necessary.
  $conditions = new Condition('AND');
  $conditions
    ->condition('aid', $aid);
  if ($id) {
    $conditions
      ->condition($sql['id'], $id);
  }
  $query
    ->condition($conditions);
  $result = $query
    ->execute();
  while ($oid = $result
    ->fetchField()) {

    // Don't delete the adjustments one at a time. We'll do it in bulk soon for
    // efficiency.
    uc_attribute_subject_option_delete($oid, $type, $id, FALSE);
  }
  $connection
    ->delete($sql['attr_table'])
    ->condition($conditions)
    ->execute();

  // If this is a product attribute, wipe any associated adjustments.
  if ($type == 'product') {
    uc_attribute_adjustments_delete([
      'aid' => $aid,
      'nid' => $id,
    ]);
  }
  return SAVED_DELETED;
}

/**
 * Loads a product/class attribute option.
 *
 * @param int $oid
 *   The product/class attribute option ID.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param int $id
 *   The product/class ID.
 *
 * @return object
 *   An object containing the product/class attribute option.
 */
function uc_attribute_subject_option_load($oid, $type, $id) {
  $sql = uc_attribute_type_info($type);
  $connection = \Drupal::database();
  $query = $connection
    ->select($sql['opt_table'], 'po');
  $query
    ->leftJoin('uc_attribute_options', 'ao', 'po.oid = ao.oid');
  $query
    ->fields('po', [
    $sql['id'],
    'oid',
    'cost',
    'price',
    'weight',
    'ordering',
  ])
    ->fields('ao', [
    'name',
    'aid',
  ])
    ->condition('po.oid', $oid)
    ->condition("po.{$sql['id']}", $id)
    ->orderBy('po.ordering')
    ->orderBy('ao.name');
  return $query
    ->execute()
    ->fetchObject();
}

/**
 * Saves a product/class attribute option.
 *
 * @param &$option
 *   The product/class attribute option.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param int $id
 *   The product/class ID.
 *
 * @return \Drupal\Core\Database\StatementInterface|null
 *   A prepared statement, or NULL if the query is not valid.
 */
function uc_attribute_subject_option_save(&$option, $type, $id) {
  $sql = uc_attribute_type_info($type);
  $connection = \Drupal::database();
  return $connection
    ->merge($sql['opt_table'])
    ->keys([
    $sql['id'] => $id,
    'oid' => $option->oid,
  ])
    ->fields([
    'cost' => $option->cost,
    'price' => $option->price,
    'weight' => $option->weight,
    'ordering' => $option->ordering,
  ])
    ->execute();
}

/**
 * Deletes a product/class attribute option.
 *
 * @param $oid
 *   The base attribute's option ID.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param int $id
 *   The product/class ID.
 *
 * @return int
 *   The Drupal SAVED_DELETED flag.
 */
function uc_attribute_subject_option_delete($oid, $type, $id = NULL, $adjustments = TRUE) {
  $sql = uc_attribute_type_info($type);

  // Delete the option.
  $connection = \Drupal::database();
  $query = $connection
    ->delete($sql['opt_table'])
    ->condition('oid', $oid);

  // Base conditions, and an ID check if necessary.
  if ($id) {
    $query
      ->condition($sql['id'], $id);
  }
  $query
    ->execute();

  // If this is a product, clean up the associated adjustments.
  if ($adjustments && $type == 'product') {
    uc_attribute_adjustments_delete([
      'aid' => uc_attribute_option_load($oid)->aid,
      'oid' => $oid,
      'nid' => $id,
    ]);
  }
  return SAVED_DELETED;
}

/**
 * Deletes an attribute adjustment.
 *
 * @param array $fields
 *   Fields used to build a condition to delete adjustments against. Fields
 *   currently handled are 'aid', 'oid', and 'nid'.
 *
 * @return int
 *   The Drupal SAVED_DELETED flag.
 */
function uc_attribute_adjustments_delete(array $fields) {

  // Build the serialized string to match against adjustments.
  $match = '';
  if (!empty($fields['aid'])) {
    $match .= serialize((int) $fields['aid']);
  }
  if (!empty($fields['oid'])) {
    $match .= serialize((string) $fields['oid']);
  }

  // Assemble the conditions and args for the SQL.
  $connection = \Drupal::database();
  $query = $connection
    ->delete('uc_product_adjustments');

  // If we have to match aid or oid...
  if ($match) {
    $query
      ->condition('combination', '%' . $connection
      ->escapeLike($match) . '%', 'LIKE');
  }

  // If we've got a node ID to match.
  if (!empty($fields['nid'])) {
    $query
      ->condition('nid', $fields['nid']);
  }

  // Delete what's necessary.
  if ($query
    ->conditions()) {
    $query
      ->execute();
  }
  return SAVED_DELETED;
}

/**
 * Checks if a product/class attribute exists.
 *
 * @param int $aid
 *   The base attribute ID.
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 * @param int $id
 *   The product/class attribute's ID.
 *
 * @return bool
 *   TRUE if the attribute exists.
 */
function uc_attribute_subject_exists($aid, $type, $id) {
  $sql = uc_attribute_type_info($type);
  $connection = \Drupal::database();
  $query = $connection
    ->select($sql['attr_table'], 'a')
    ->fields('a', [
    'aid',
  ])
    ->condition('aid', $aid)
    ->condition($sql['id'], $id);
  return FALSE !== $query
    ->execute()
    ->fetchField();
}

/**
 * Returns a list of names to abstract queries between products and classes.
 *
 * @param string $type
 *   The type of attribute: 'product' or 'class'. Any other type will fetch
 *   a base attribute.
 *
 * @return array
 *   Array of information helpful for creating SQL queries dealing
 *   with attributes.
 */
function uc_attribute_type_info($type) {
  switch ($type) {
    case 'product':
      return [
        'attr_table' => 'uc_product_attributes',
        'opt_table' => 'uc_product_options',
        'id' => 'nid',
      ];
    case 'class':
      return [
        'attr_table' => 'uc_class_attributes',
        'opt_table' => 'uc_class_attribute_options',
        'id' => 'pcid',
      ];
  }
}

/**
 * Loads all attributes associated with a product node.
 *
 * @param int $nid
 *   The product node id.
 *
 * @return array
 *   The attributes.
 */
function uc_product_get_attributes($nid) {
  $attributes = [];
  $connection = \Drupal::database();
  $result = $connection
    ->query("SELECT upa.aid FROM {uc_product_attributes} upa LEFT JOIN {uc_attributes} ua ON upa.aid = ua.aid WHERE upa.nid = :nid ORDER BY upa.ordering, ua.name", [
    ':nid' => $nid,
  ]);
  foreach ($result as $attribute) {
    $attributes[$attribute->aid] = uc_attribute_load($attribute->aid, $nid, 'product');
  }
  return $attributes;
}

/**
 * Loads all attributes associated with a product class.
 *
 * @param int $pcid
 *   The product class id.
 *
 * @return array
 *   The attributes.
 */
function uc_class_get_attributes($pcid) {
  $attributes = [];
  $connection = \Drupal::database();
  $result = $connection
    ->query("SELECT uca.aid FROM {uc_class_attributes} uca LEFT JOIN {uc_attributes} ua ON uca.aid = ua.aid WHERE uca.pcid = :type ORDER BY uca.ordering, ua.name", [
    ':type' => $pcid,
  ]);
  foreach ($result as $attribute) {
    $attributes[$attribute->aid] = uc_attribute_load($attribute->aid, $pcid, 'class');
  }
  return $attributes;
}

/**
 * Gets the options chosen for a product that is in the cart.
 *
 * @param mixed $item
 *   A product node, a cart item or an ordered product object.
 *
 * @return array
 *   Array of options chosen by a customer, indexed by attribute ids. Each
 *   element stores the attribute name and the option object chosen.
 */
function _uc_cart_product_get_options($item) {
  if ($item instanceof NodeInterface) {
    $node = $item;
    $attributes = $item->data['attributes'];
  }
  else {
    $node = $item->nid->entity;
    $attributes = $item->data->attributes;
  }
  $options = [];
  $index = 0;
  if (!empty($attributes)) {
    foreach ($attributes as $aid => $selected) {
      if (isset($node->attributes[$aid])) {
        $attribute = $node->attributes[$aid];
        $name = _uc_attribute_get_name($attribute);

        // Only discrete options can affect the price of an item.
        if ($attribute->display && count($attribute->options)) {

          // There may be many selected options, or just one.
          foreach ((array) $selected as $oid) {
            if ($oid > 0) {
              $options[$index] = (array) $attribute->options[$oid];
              $options[$index]['attribute'] = $name;
              $index++;
            }
          }
        }
        else {

          // Handle textfield attributes.
          $options[$index] = [
            'attribute' => $name,
            'aid' => $aid,
            'oid' => 0,
            'name' => $selected,
            'cost' => 0,
            'price' => 0,
            'weight' => 0,
          ];
        }
        $index++;
      }
    }
  }
  return $options;
}

/**
 * Ajax callback for attribute selection form elements.
 */
function uc_attribute_option_ajax($form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $triggering_element = $form_state
    ->getTriggeringElement();
  $parents = $triggering_element['#array_parents'];
  $wrapper = '#' . $triggering_element['#ajax']['wrapper'];
  while ($key = array_pop($parents)) {
    if ($key == 'attributes') {
      array_push($parents, $key);
      $element = NestedArray::getValue($form, $parents);
      $response
        ->addCommand(new ReplaceCommand($wrapper, drupal_render($element)));
      break;
    }
  }
  if (strpos($form['#form_id'], 'add_to_cart_form') !== FALSE) {
    uc_product_view_ajax_commands($response, $form_state, [
      'display_price',
      'weight',
      'cost',
    ]);
  }
  $status_messages = [
    '#type' => 'status_messages',
  ];
  $response
    ->addCommand(new PrependCommand($wrapper, drupal_render($status_messages)));
  return $response;
}

/**
 * Helper function for uc_attribute_form_alter().
 *
 * @param $id
 *   The unique id to use to wrap these form elements.
 * @param &$product
 *   The product node for which the attribute form elements are to be attached.
 * @param bool $use_ajax
 *   TRUE to add ajax to the form. Note that ajax may be added even if this is
 *   FALSE, if there are multiple attributes and one or more of them is set to
 *   display total price.
 *
 * @return array
 *   Form API array with attribute elements to add to the product form.
 *
 * @see uc_attribute_option_ajax()
 */
function _uc_attribute_alter_form($id, &$product, $use_ajax) {

  // If the product doesn't have attributes, return the form as it is.
  if (empty($product->attributes) || !is_array($product->attributes)) {
    return [];
  }
  $nid = $product
    ->id();
  $attributes = $product->attributes;
  $priced_attributes = uc_attribute_priced_attributes($nid);

  // If the form is being built for the first time, populate attributes
  // with their default values.
  if (!isset($product->data['attributes'])) {
    $values = [];
    foreach ($priced_attributes as $aid) {
      if (!$attributes[$aid]->required && ($attributes[$aid]->display == 1 || $attributes[$aid]->display == 2)) {
        $values[$aid] = $attributes[$aid]->default_option;
      }
    }
    if (!empty($values)) {
      $data = $product->data;
      $data['attributes'] = $values;
      if (isset($product->qty)) {

        // Preserve the quantity (for product-kit sub-products).
        $qty = $product->qty;
      }
      $product = uc_product_load_variant($product
        ->id(), $data);
      if (isset($qty)) {
        $product->qty = $qty;
      }
    }
  }
  if (empty($product->data) || !is_array($product->data)) {
    $product->data = [];
  }

  // Initialize the form element.
  $form_attributes = [
    '#type' => 'container',
    '#attributes' => [
      'id' => $id,
      'class' => [
        'product-attributes',
      ],
    ],
  ];
  $price_format = \Drupal::config('uc_attribute.settings')
    ->get('option_price_format');

  // Loop through each product attribute and generate its form element.
  foreach ($attributes as $attribute) {

    // Build the attribute's options array.
    $options = [];
    foreach ($attribute->options as $option) {
      $display_price = '';
      if (in_array($attribute->aid, $priced_attributes)) {
        $data = [
          'display_only' => TRUE,
        ] + $product->data;
        if (empty($data['attributes'])) {
          $data['attributes'] = [];
        }
        switch ($price_format) {
          case 'total':

            // Only display total price for non-checkbox options.
            // @todo Fix attribute option total price display for product kits.
            if ($attribute->display != 3 && !isset($product->data['kit_id'])) {
              $use_ajax = $use_ajax || count($priced_attributes) > 1;
              $data['attributes'] = [
                $attribute->aid => $option->oid,
              ] + $data['attributes'];
              $variant = uc_product_load_variant($product
                ->id(), $data);
              $display_price = uc_currency_format($variant->display_price);
              break;
            }
          case 'adjustment':
            if ($attribute->display == 3 || !$use_ajax) {

              // For checkboxes, or if the node totals are not being updated,
              // we compare this attribute against base price.
              if (empty($base)) {

                // Only build the base once.
                unset($data['attributes']);
                $base = uc_product_load_variant($product
                  ->id(), $data);
              }
              $data['attributes'] = [
                $attribute->aid => $option->oid,
              ];
              $variant = uc_product_load_variant($product
                ->id(), $data);
              $adjustment = $variant->display_price - $base->display_price;
            }
            else {

              // Otherwise we compare against current total price.
              if (empty($selected)) {
                $selected = uc_product_load_variant($product
                  ->id(), $data);
              }
              $data['attributes'] = [
                $attribute->aid => $option->oid,
              ] + $data['attributes'];
              $variant = uc_product_load_variant($product
                ->id(), $data);
              $adjustment = $variant->display_price - $selected->display_price;
            }
            if ($adjustment != 0) {
              $display_price = $adjustment > 0 ? '+' : '-';
              $display_price .= uc_currency_format(abs($adjustment));
            }
            break;
        }
      }

      // Select options are sanitized, but radio button labels are not.
      $build = [
        '#theme' => 'uc_attribute_option',
        '#option' => $attribute->display == 2 ? SafeMarkup::checkPlain($option->name) : $option->name,
        '#price' => $display_price,
      ];
      $options[$option->oid] = drupal_render($build);
    }
    if (count($attribute->options) && $attribute->display > 0) {
      if ($attribute->required) {
        if ($attribute->display == 1) {
          $options = [
            '' => t('Please select'),
          ] + $options;
        }
        $attribute->default_option = NULL;
      }
      $attr_type = '';
      switch ($attribute->display) {
        case 1:
          $attr_type = 'select';
          break;
        case 2:
          $attr_type = 'radios';
          break;
        case 3:
          $attr_type = 'checkboxes';
          $attribute->default_option = [];
          break;
      }
      $form_attributes[$attribute->aid] = [
        '#type' => $attr_type,
        '#default_value' => $attribute->default_option,
        '#options' => $options,
      ];
      if ($use_ajax) {
        $form_attributes[$attribute->aid]['#ajax'] = [
          'callback' => 'uc_attribute_option_ajax',
          'wrapper' => $id,
        ];
      }
    }
    elseif ($attribute->display > 0) {
      $form_attributes[$attribute->aid] = [
        '#type' => 'textfield',
        '#default_value' => '',
      ];
      if (!$attribute->required && isset($attribute->options[$attribute->default_option])) {
        $form_attributes[$attribute->aid]['#default_value'] = $attribute->options[$attribute->default_option]->name;
      }
    }
    else {
      $form_attributes[$attribute->aid] = [
        '#type' => 'textfield',
        '#default_value' => '',
      ];
    }
    $name = _uc_attribute_get_name($attribute, FALSE);
    if (!is_null($name)) {
      $form_attributes[$attribute->aid]['#title'] = SafeMarkup::checkPlain($name);
    }
    $form_attributes[$attribute->aid]['#description'] = Xss::filter($attribute->description);
    $form_attributes[$attribute->aid]['#required'] = $attribute->required;
  }
  return $form_attributes;
}

/**
 * Returns an array of display types used as options when creating attributes.
 *
 * @return array
 *   Array of display types used as options when creating attributes.
 */
function _uc_attribute_display_types() {
  return [
    0 => t('Text field'),
    1 => t('Select box'),
    2 => t('Radio buttons'),
    3 => t('Checkboxes'),
  ];
}

/**
 * Gets the price affecting attributes for a product.
 *
 * @param int $nid
 *   The nid of a product.
 *
 * @return array
 *   Array of attribute ids that have price affecting options.
 */
function uc_attribute_priced_attributes($nid) {
  $connection = \Drupal::database();
  $aids = $connection
    ->query("SELECT DISTINCT (pa.aid) FROM {uc_product_attributes} pa INNER JOIN {uc_attribute_options} ao ON ao.aid = pa.aid INNER JOIN {uc_product_options} po ON (po.oid = ao.oid AND po.nid = pa.nid) WHERE pa.nid = :nid AND po.price <> :price AND pa.display <> :display", [
    ':nid' => $nid,
    ':price' => 0,
    ':display' => 0,
  ])
    ->fetchCol();
  return $aids;
}

/**
 * Returns the attribute name to display.
 *
 * An attribute with a label set returns that label except when set to
 * '<none>' . In this case, a NULL is returned. The $title argument forces the
 * function to return the name property instead of label when label is set to
 * '<none>'.
 *
 * The NULL return value is typically used by forms so they know to hide the
 * #title property of the element.
 *
 * @param object $attribute
 *   Attribute object.
 * @param bool $title
 *   TRUE indicates the function is to return the attribute name when its label
 *   is set to '<none>'.
 *
 * @return string|null
 *   When the attribute label is set and not '<none>', it is returned.
 *   Otherwise, the attribute name is returned when $title is TRUE and NULL is
 *   returned when $title is FALSE.
 */
function _uc_attribute_get_name($attribute, $title = TRUE) {
  if (!$title && $attribute->label == '<none>') {
    return NULL;
  }
  else {
    return empty($attribute->label) || $attribute->label == '<none>' && $title ? $attribute->name : $attribute->label;
  }
}

Functions

Namesort descending Description
uc_attribute_adjustments_delete Deletes an attribute adjustment.
uc_attribute_buy_it_now_form_validate Validation callback for "buy it now" forms with attributes.
uc_attribute_delete Deletes an attribute from the database.
uc_attribute_form_uc_product_buy_it_now_form_alter Implements hook_form_BASE_FORM_ID_alter() for uc_product_buy_it_now_form().
uc_attribute_form_uc_product_settings_form_alter Implements hook_form_FORM_ID_alter() for uc_product_settings_form().
uc_attribute_help Implements hook_help().
uc_attribute_load Loads an attribute from the database.
uc_attribute_load_multiple Loads attribute objects from the database.
uc_attribute_load_product_attributes Fetches an array of attribute objects that belong to a product.
uc_attribute_module_implements_alter Implements hook_module_implements_alter().
uc_attribute_node_delete Implements hook_node_delete().
uc_attribute_node_insert Implements hook_node_insert().
uc_attribute_node_load Implements hook_node_load().
uc_attribute_node_type_delete Implements hook_node_type_delete().
uc_attribute_node_update_index Implements hook_node_update_index().
uc_attribute_option_ajax Ajax callback for attribute selection form elements.
uc_attribute_option_delete Deletes an attribute option from the database.
uc_attribute_option_load Loads an attribute option from the database.
uc_attribute_option_save Saves an attribute object to the database.
uc_attribute_priced_attributes Gets the price affecting attributes for a product.
uc_attribute_save Saves an attribute object to the database.
uc_attribute_subject_delete Deletes an attribute and all options associated with it.
uc_attribute_subject_exists Checks if a product/class attribute exists.
uc_attribute_subject_option_delete Deletes a product/class attribute option.
uc_attribute_subject_option_load Loads a product/class attribute option.
uc_attribute_subject_option_save Saves a product/class attribute option.
uc_attribute_subject_save Saves a product/class attribute.
uc_attribute_theme Implements hook_theme().
uc_attribute_type_info Returns a list of names to abstract queries between products and classes.
uc_attribute_uc_add_to_cart_data Implements hook_uc_add_to_cart_data().
uc_attribute_uc_form_alter Implements hook_uc_form_alter().
uc_attribute_uc_order_product_alter Implements hook_uc_order_product_alter().
uc_attribute_uc_product_alter Implements hook_uc_product_alter().
uc_attribute_uc_product_description Implements hook_uc_product_description().
uc_attribute_uc_product_models Implements hook_uc_product_models().
uc_attribute_uc_product_settings_form_submit Submit handler for product attribute settings.
uc_class_get_attributes Loads all attributes associated with a product class.
uc_product_get_attributes Loads all attributes associated with a product node.
_uc_attribute_alter_form Helper function for uc_attribute_form_alter().
_uc_attribute_display_types Returns an array of display types used as options when creating attributes.
_uc_attribute_get_name Returns the attribute name to display.
_uc_cart_product_get_options Gets the options chosen for a product that is in the cart.