fontana_commerce.module
Thu Jan 20 2022 14:57:39 GMT+0000 (UTC)
<?php /** * @file * Contains fontana_commerce.module. */ use Drupal\commerce\EntityHelper; use Drupal\Component\Render\FormattableMarkup; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\RedirectCommand; use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\Display\EntityViewDisplayInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\commerce_product\Entity\ProductVariationInterface; /** * Implements hook_views_data_alter(). */ function fontana_commerce_views_data_alter(array &$data) { $data['views']['custom_category_filter'] = [ 'title' => t('Custom category filter'), 'filter' => [ 'title' => t('Custom category filter'), 'help' => t('Provides a custom filter logic.'), 'field' => 'nid', 'id' => 'category_views_filter', ], ]; $data['views']['sku_filter'] = [ 'title' => t('SKU filter'), 'filter' => [ 'title' => t('SKU filter'), 'help' => t('Provides a custom filter for filtering orders by sku.'), 'field' => 'id', 'id' => 'sku_filter', ], ]; $data['commerce_shipment']['shipping_profile'] = [ 'title' => t('Shipping Profile'), 'help' => t('Reference to the shipping profile of a commerce shipment.'), 'relationship' => [ 'group' => 'Shipment', // Views name of the table being joined to from commerce_shipment. 'base' => 'profile', // Database field name in profile for the join. 'base field' => 'profile_id', // Real database field name in commerce_shipment for the join, to override // 'unique_dummy_name'. 'field' => 'shipping_profile__target_id', // ID of relationship handler plugin to use. 'id' => 'standard', 'label' => t('Shipping Profile'), ], ]; $data['commerce_order']['quick_view'] = [ 'title' => t('Quick view'), 'field' => [ 'id' => 'commerce_order_quick_view', ], ]; $data['commerce_order']['update_state']['field'] = [ 'title' => t('Update state'), 'help' => t('Add buttons for update the order state.'), 'id' => 'commerce_order_update_state', ]; } /** * Implements hook_entity_extra_field_info(). */ function fontana_commerce_entity_extra_field_info() { $extra = []; $extra['commerce_product']['default']['display']['manufacturer_declaration'] = [ 'label' => t('Manufacturer(display: declaration)'), 'visible' => FALSE, ]; $extra['commerce_product']['default']['display']['variation_sizes'] = [ 'label' => t('Product variations size attribute'), 'visible' => TRUE, ]; $extra['commerce_product']['default']['display']['variation_colors'] = [ 'label' => t('Product variations color attribute'), 'visible' => TRUE, ]; return $extra; } /** * Implements hook_entity_view(). */ function fontana_commerce_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) { if ($entity->getEntityTypeId() === 'commerce_product' && $entity->bundle() === 'default' && $display->getComponent('manufacturer_declaration')) { if ($entity->hasField('field_manufacturer')) { /** @var \Drupal\taxonomy\Entity\Term $manufacturer */ if ($manufacturer = $entity->get('field_manufacturer')->entity) { $view_builder = \Drupal::entityTypeManager()->getViewBuilder('taxonomy_term'); $build['manufacturer_declaration'] = $view_builder->view($manufacturer, 'declaration'); } } } if ($view_mode === 'teaser' && $entity->getEntityTypeId() === 'commerce_product' && $entity->bundle() === 'default') { $sizes = []; $colors = []; /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */ foreach ($entity->getVariations() as $variation) { if ($size = $variation->getAttributeValue('attribute_size')) { $sizes[] = $size->label(); } if ($color = $variation->getAttributeValue('attribute_boja')) { $colors[] = $color->label(); } } if ($display->getComponent('variation_sizes')) { $build['variation_sizes'] = [ '#type' => 'html_tag', '#tag' => 'div', '#value' => implode(', ', array_unique($sizes)), '#attributes' => [ 'class' => ['size-wrapper'], ], ]; } if ($display->getComponent('variation_colors')) { $build['variation_colors'] = [ '#type' => 'html_tag', '#tag' => 'div', '#value' => implode(', ', array_unique($colors)), '#attributes' => [ 'class' => ['color-wrapper'], ], ]; } } } /** * Implements hook_form_alter(). */ function fontana_commerce_form_alter(&$form, FormStateInterface $form_state, $form_id) { // Get add to cart form from product page. if ( str_contains($form_id, "commerce_order_item_dc_ajax_add_cart_form_commerce_product") || str_contains($form_id, 'commerce_order_item_add_to_cart_form_commerce_product') ) { // Check if product contain variations. if (isset($form['purchased_entity']['widget'][0]['variation']['#options'])) { // Get variations. $variations = $form['purchased_entity']['widget'][0]['variation']['#options']; foreach ($variations as $key => $item) { // Load variation by key(id). $variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load($key); // Set boja if exists. !empty($variation->get('attribute_boja')->target_id) ? $color = $variation->get('attribute_boja')->entity->getName() : $color = ""; // Set size if exists. !empty($variation->get('attribute_size')->target_id) ? $size = $variation->get('attribute_size')->entity->getName() : $size = ""; // If both fields are empty use default option. if (!empty($size) || !empty($color)) { $form['purchased_entity']['widget'][0]['variation']['#options'][$key] = $size . " " . $color; } $item_title = $variation->getTitle(); $variation_images = $variation->get('field_image')->getValue(); $images = []; foreach ($variation_images as $image) { if (empty($image['title'])) { $image['title'] = $item_title; } if (empty($image['alt'])) { $image['alt'] = $item_title; } $images[] = $image; } $variation->set('field_image', $images); } } if (isset($form['purchased_entity']['widget'][0]['variation'])) { if (isset($form['purchased_entity']['widget'][0]['variation']['#value'])) { $variation_id = $form['purchased_entity']['widget'][0]['variation']['#value']; } else { $variation_id = $form['purchased_entity']['widget'][0]['variation']['#default_value']; } $variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load($variation_id); $square_meter_per_box = $variation->get('field_square_meters_per_box')->value; if (!empty($square_meter_per_box)) { $form['quantity']['widget'][0]['value']['#step'] = '0.01'; } } } // Get checkout flow form and step order information. if ($form_id == 'commerce_checkout_flow_multistep_default' && $form['#step_id'] == 'order_information') { $form['actions']['captcha'] = [ '#type' => 'captcha', '#captcha_type' => 'recaptcha/reCAPTCHA', ]; } if ($form_id == 'commerce_order_default_edit_form') { $order_id = \Drupal::routeMatch()->getRawParameter('commerce_order'); $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($order_id); $payment_gateway = $order->payment_gateway->first()->entity; if (!empty($payment_gateway)) { $payment_label = $payment_gateway->label(); $form['payment_gateway'] = [ '#type' => 'details', '#group' => 'advanced', '#open' => TRUE, '#title' => t('Payment Method'), 'payment_gateway' => [ '#type' => 'item', '#markup' => $payment_label, ], ]; } } $input = $form_state->getUserInput(); $is_ajax = (bool) ($input['_drupal_ajax'] ?? FALSE); if (str_contains($form_id, 'state_machine_transition_form_commerce_order_state') && $is_ajax) { foreach ($form['actions'] as $name => $action) { if (strpos($name, '#') !== FALSE) { continue; } $form['actions'][$name]['#ajax'] = [ 'callback' => 'fontana_commerce_order_state_ajax', ]; } } } /** * Ajax callback for the order state form. * * @param array $form * The form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. * * @return \Drupal\Core\Ajax\AjaxResponse * The ajax response. */ function fontana_commerce_order_state_ajax(array $form, FormStateInterface $form_state) { $response = new AjaxResponse(); $destination = \Drupal::request()->query->get('destination'); $response->addCommand(new RedirectCommand($destination)); return $response; } /** * Implements hook_element_info_alter(). */ function fontana_commerce_element_info_alter(array &$info) { if (isset($info['address'])) { $info['address']['#process'][] = 'fontana_commerce_make_address_line2_visible'; } } /** * Process callback for address element. */ function fontana_commerce_make_address_line2_visible(array &$element, FormStateInterface $form_state, array &$complete_form) { $element['address_line2']['#title_display'] = 'before'; return $element; } /** * Implements hook_preprocess_HOOK(). */ function fontana_commerce_preprocess_commerce_product(&$variables) { /** @var \Drupal\commerce_product\Entity\ProductInterface $product_entity */ $product_entity = $variables['product_entity']; $variation = $product_entity->getDefaultVariation(); if (!$variation instanceof ProductVariationInterface) { $variables['calculator_visible'] = FALSE; } else { /** @var \Drupal\presentcommerce_box_calculator\Service\BoxCalculator $box_calculator */ $box_calculator = \Drupal::service('presentcommerce_box_calculator.box_calculator'); if ($box_calculator->isVisible($variation)) { $variables['calculator_visible'] = TRUE; } else { $variables['calculator_visible'] = FALSE; } } } /** * Implements hook_entity_presave(). */ function fontana_commerce_entity_presave(EntityInterface $entity) { // Check if entity is product variation and if autogenerate title is selected. if ($entity->getEntityTypeId() == "commerce_product_variation" && $entity->get('field_auto_generate_title')->value == TRUE) { $title = generate_variation_title($entity); $entity->setTitle($title); } elseif ($entity->getEntityTypeId() == "commerce_product_variation") { $title_alt = generate_image_title_alt($entity); if ($title_alt !== "") { $entity->set('field_image', $title_alt); } } if ($entity->getEntityTypeId() == 'commerce_product') { $userId = \Drupal::currentUser()->id(); $user = \Drupal::entityTypeManager()->getStorage('user')->load($userId); $entity->set('field_updated_by', $user); } if ($entity->getEntityTypeId() == 'commerce_order_item' && $entity->getPurchasedEntity()->get('field_square_meters_per_box')->value !== NULL) { $quantity = $entity->getQuantity(); $product = \Drupal::entityTypeManager() ->getStorage('commerce_product_variation') ->load($entity->getPurchasedEntityId()); $square_meters = $product->get('field_square_meters_per_box')->value; $number_of_boxes = (integer) round($quantity / $square_meters); if ($number_of_boxes < 1) { $number_of_boxes = 1; } $entity->set('field_number_of_boxes', $number_of_boxes); } } /** * Generate Variation title based on attributes. */ function generate_variation_title(EntityInterface $entity) { if (!$entity->getProductId()) { // Title generation is not possible before the parent product is known. return ''; } $product_title = $entity->getProduct()->getTitle(); if ($attribute_values = $entity->getAttributeValues()) { $attribute_labels = EntityHelper::extractLabels($attribute_values); $title = $product_title . ' - ' . implode(', ', $attribute_labels); } else { // When there are no attribute fields, there's only one variation. $title = $product_title; } return $title; } /** * Generate Variation title based on attributes. */ function generate_image_title_alt(EntityInterface $entity) { if (!$entity->getProductId()) { // Title generation is not possible before the parent product is known. return ''; } $product_title = $entity->getProduct()->getTitle(); $variation_images = $entity->get('field_image')->getValue(); $images = reset($variation_images); foreach ($variation_images as $image) { if (empty($image['alt'])) { $image['alt'] = $product_title; } if (empty($image['title'])) { $image['title'] = $product_title; } $images[] = $image; } return $images; } /** * Implements hook_page_attachments(). */ function fontana_commerce_page_attachments(array &$attachments) { $config = \Drupal::config('system.theme'); $theme = \Drupal::theme()->getActiveTheme()->getName(); if ($theme == $config->get('admin')) { $attachments['#attached']['library'][] = 'fontana_commerce/extra.admin'; } } /** * Implements hook_field_widget_form_alter(). */ function fontana_commerce_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) { // Fix problem with displaying description on shipping pane // for single shipping method. if ($context['items']->getFieldDefinition()->getName() === 'shipping_method' && $context['items']->getFieldDefinition()->getTargetEntityTypeId() === 'commerce_shipment') { foreach ($element['#options'] as $key => $option) { $title = $element[$key]["#rate"]->getService()->getLabel(); $option = (new FormattableMarkup('@service @amount', [ '@service' => $title, '@amount' => '', ])); $element['#options'][$key] = $option; } } } /** * Implements hook_form_BASE_FORM_ID_alter(). */ function fontana_commerce_form_views_form_commerce_cart_form_default_alter(&$form, FormStateInterface $form_state) { $order_items = $form['output'][0]['#view']->result[0]->_entity->getItems(); foreach ($order_items as $key => $order_item) { $purchased_entity = $order_item->getPurchasedEntity(); if (!empty($purchased_entity->get('field_square_meters_per_box')->getValue())) { $form['edit_quantity'][$key]['#step'] = '0.01'; } } }
Comments