You are here

dc_ajax_add_cart.module in Commerce Ajax Add to Cart 8

Same filename and directory in other branches
  1. 7.2 dc_ajax_add_cart.module
  2. 7 dc_ajax_add_cart.module

Ajax add to cart module.

Allows you to add products AJAX-ically to cart. You can remove products AJAX-ically from cart.

File

dc_ajax_add_cart.module
View source
<?php

/**
 * @file
 * Ajax add to cart module.
 *
 * Allows you to add products AJAX-ically to cart. You can remove products
 * AJAX-ically from cart.
 */
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_entity_bundle_create().
 *
 * Creates an 'dc_ajax_add_cart' form display for each new order item type.
 */
function dc_ajax_add_cart_entity_bundle_create($entity_type_id, $bundle) {
  if ($entity_type_id == 'commerce_order_item' && !\Drupal::isConfigSyncing()) {
    $storage = \Drupal::service('entity_type.manager')
      ->getStorage('entity_form_display');
    $form_display = $storage
      ->load('commerce_order_item.' . $bundle . '.dc_ajax_add_cart');
    if (!$form_display) {

      /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
      $form_display = $storage
        ->create([
        'targetEntityType' => 'commerce_order_item',
        'bundle' => $bundle,
        'mode' => 'dc_ajax_add_cart',
        'status' => TRUE,
      ]);
      $form_display
        ->save();
    }
  }
}

/**
 * Implements hook_entity_type_build().
 */
function dc_ajax_add_cart_entity_type_build(array &$entity_types) {
  $entity_types['commerce_order_item']
    ->setFormClass('dc_ajax_add_cart', '\\Drupal\\dc_ajax_add_cart\\Form\\AjaxAddToCartForm');
}

/**
 * Implements hook_form_FORM_ID_alter() for 'entity_form_display_edit_form'.
 *
 * Hides irrelevant purchased_entity widgets on the dc_ajax_add_cart order item
 * form display.
 */
function dc_ajax_add_cart_form_entity_form_display_edit_form_alter(array &$form, FormStateInterface $form_state) {

  /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $entity */
  $entity = $form_state
    ->getFormObject()
    ->getEntity();
  if ($form['#entity_type'] == 'commerce_order_item' && $entity
    ->getMode() == 'dc_ajax_add_cart') {
    $options =& $form['fields']['purchased_entity']['plugin']['type']['#options'];
    unset($options['commerce_entity_select']);
    unset($options['entity_reference_autocomplete_tags']);
    unset($options['entity_reference_autocomplete']);
    unset($options['inline_entity_form_complex']);
    unset($options['options_buttons']);
    unset($options['options_select']);
  }
}