Skip to content

Instantly share code, notes, and snippets.

@lisastreeter
Last active January 26, 2018 16:42
Show Gist options
  • Save lisastreeter/c6a2482a3eba4da372b6f3c77a9cb2b7 to your computer and use it in GitHub Desktop.
Save lisastreeter/c6a2482a3eba4da372b6f3c77a9cb2b7 to your computer and use it in GitHub Desktop.
Custom entity reference field widget for inventory size basis product field
<?php
namespace Drupal\wbc_custom\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
/**
* Plugin implementation of the 'product_inventory_size_basis' widget.
*
* @FieldWidget(
* id = "product_inventory_size_basis",
* label = @Translation("Inventory size basis"),
* description = @Translation("An autocomplete text field."),
* field_types = {
* "entity_reference"
* }
* )
*/
class ProductInventorySizeBasisWidget extends EntityReferenceAutocompleteWidget {
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
$entity_type = $field_definition->getTargetEntityTypeId();
$field_name = $field_definition->getName();
return $entity_type == 'commerce_product' && $field_name == 'field_inventory_size_basis';
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
if (!$items[$delta]->getEntity()->isNew()) {
$element['target_id']['#disabled'] = TRUE;
}
return $element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment