Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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