Skip to content

Instantly share code, notes, and snippets.

@drugan
Created August 31, 2017 16:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drugan/8c2ca6d741440f380e8518ccc2061861 to your computer and use it in GitHub Desktop.
Save drugan/8c2ca6d741440f380e8518ccc2061861 to your computer and use it in GitHub Desktop.
The filed widget defines how a field or collections of fields are displayed on the form. As an example is taken ProductVariationAttributesWidget of the Commerce 2.x module.
<?php
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
*
* Place this code into YOUR_MODULE.module file replacing YOUR_MODULE placeholder
* with your modules' name.
*/
function YOUR_MODULE_field_widget_commerce_product_variation_attributes_form_alter(&$element, FormStateInterface $form_state, $context) {
// Make ajax responsive changes on attribute fields' properties.
// @see \Drupal\commerce_product\Plugin\Field\FieldWidget\ProductVariationAttributesWidget->formElement()
foreach ( $context['items']->getEntity()->getPurchasedEntity()->getAttributeValueIds() as $name => $id) {
$label = $element['attributes'][$name]['#options'][$element['attributes'][$name]['#default_value']];
// Prettify the attribute title.
$element['attributes'][$name]['#title'] = t("@label is a great choice for the @title!", ['@label' => $label, '@title' => $element['attributes'][$name]['#title']]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment