Skip to content

Instantly share code, notes, and snippets.

@joshmiller83
Last active May 31, 2019 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshmiller83/8a80fa2e77edab902fa40aa7f51e74eb to your computer and use it in GitHub Desktop.
Save joshmiller83/8a80fa2e77edab902fa40aa7f51e74eb to your computer and use it in GitHub Desktop.
Add to cart modifications for Commerce 2
<?php
/**
* Implements hook_entity_type_alter().
*/
function modulename_entity_type_alter(array &$entity_types) {
$entity_types['commerce_order_item']->setFormClass('add_to_cart', '\Drupal\modulename\Form\ModulenameAddToCartForm');
}
<?php
// In folder `src/Form/`.
namespace Drupal\modulename\Form;
use Drupal\commerce\Context;
use Drupal\commerce_cart\Form\AddToCartForm;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Markup;
/**
* Class ModulenameAddToCartForm.
*
* @package Drupal\modulename\Form
*/
class ModulenameAddToCartForm extends AddToCartForm {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$form['newthing'] = ['#markup' => $this->t('Hello World')];
return $form;
}
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions = parent::actions($form, $form_state);
if (TRUE) {
$actions['submit']['#value'] = $this->t('Buy a thing');
}
return $actions;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
/** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
$order_item = $this->entity;
if ($this->orderTypeResolver->resolve($order_item) === 'something') {
$form_state->setRedirect('commerce_cart.page');
}
}
}
@travis-bradbury
Copy link

'\Drupal\modulename\Form\ModulenameAddToCartForm' should be ModulenameAddToCartForm::class to make refactoring easier.

The class' comment should say what it's for. Ie, "Class ModulenameAddToCartForm." should be "Represents a ..." or "Provides ..." https://www.drupal.org/docs/develop/standards/api-documentation-and-comment-standards#classes has a rule (use a third person verb) and https://www.drupal.org/docs/develop/standards/api-documentation-samples has a few examples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment