Last active
May 31, 2019 15:53
-
-
Save joshmiller83/8a80fa2e77edab902fa40aa7f51e74eb to your computer and use it in GitHub Desktop.
Add to cart modifications for Commerce 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
'\Drupal\modulename\Form\ModulenameAddToCartForm'
should beModulenameAddToCartForm::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.