ajax_add_to_cart.module in Ajax Add to Cart 8
Contains ajax_add_to_cart.module.
File
ajax_add_to_cart.moduleView source
<?php
/**
* @file
* Contains ajax_add_to_cart.module.
*/
use Drupal\ajax_add_to_cart\Helper\AjaxCartHelper;
use Drupal\commerce_cart\Form\AddToCartFormInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function ajax_add_to_cart_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the ajax_add_to_cart module.
case 'help.page.ajax_add_to_cart':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Add ajax add to cart functionality.') . '</p>';
return $output;
default:
}
}
/**
* Define changes for standard forms.
*/
function ajax_add_to_cart_form_alter(&$form, &$form_state, $form_id) {
// Check if the form builder implements the AddToCartFormInterface.
if ($form_state
->getBuildInfo()['callback_object'] instanceof AddToCartFormInterface) {
// Using getInstanace method to create Object.
$object = AjaxCartHelper::getInstance();
$object
->ajaxAddToCartAjaxForm($form_id, $form);
}
}
/**
* Define a validation for forms.
*/
function ajax_add_to_cart_ajax_validate(&$form, $form_state) {
$response = new AjaxResponse();
$form_id = $form_state
->getUserInput()['form_id'];
if ($form_state
->hasAnyErrors()) {
// If form is having errors, rebuild form.
$response
->addCommand(new ReplaceCommand('#commerce-product-' . $form_id, $form));
}
else {
// Using getInstanace method to create Object.
$object = AjaxCartHelper::getInstance();
// If validated successfully submit form.
$object
->ajaxAddToCartAjaxResponse($form_id, $response);
}
return $response;
}
/**
* Implements hook_preprocess_block().
*/
function ajax_add_to_cart_preprocess_block(&$vars) {
if ($vars['base_plugin_id'] == 'commerce_cart') {
// Add a class to the cart block so that we can replace it using Ajax.
$vars['attributes']['class'][] = 'block-commerce-cart';
}
}
Functions
Name | Description |
---|---|
ajax_add_to_cart_ajax_validate | Define a validation for forms. |
ajax_add_to_cart_form_alter | Define changes for standard forms. |
ajax_add_to_cart_help | Implements hook_help(). |
ajax_add_to_cart_preprocess_block | Implements hook_preprocess_block(). |