You are here

class ExampleCustomInput in Extra Field 8.2

Example Extra field form display.

This plugin provides a textual input field that is used to provide input for a hidden entity reference field. The field can be used in the user registration form. An autocomplete widget can not be used for a user facing voucher code field.

Plugin annotation


@ExtraFieldForm(
  id = "example_custom_input",
  label = @Translation("Custom input for entity reference"),
  description = @Translation("An extra field with its own validation and submit handler."),
  bundles = {
    "user.user"
  },
  visible = true
)

Hierarchy

Expanded class hierarchy of ExampleCustomInput

File

modules/extra_field_example/src/Plugin/ExtraField/Form/ExampleCustomInput.php, line 30

Namespace

Drupal\extra_field_example\Plugin\ExtraField\Form
View source
class ExampleCustomInput extends ExtraFieldFormBase implements ContainerFactoryPluginInterface {
  use StringTranslationTrait;

  /**
   * The name of the voucher code input field.
   */
  const VOUCHER_CODE_FIELD = 'voucher_code';

  /**
   * The name of the field that references a voucher code.
   */
  const VOUCHER_REFERENCE_FIELD = 'field_voucher';

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * ExampleCustomInput constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(array &$form, FormStateInterface $form_state) {
    $form[self::VOUCHER_CODE_FIELD] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Voucher code'),
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['#validate'][] = [
      $this,
      'validateVoucherCode',
    ];
  }

  /**
   * Field validation callback for voucher code.
   *
   * @param array $form
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function validateVoucherCode(array $form, FormStateInterface $form_state) {
    $voucherCode = $this
      ->lookupVoucherCodeEntity($form_state
      ->getValue('voucher_code_text'));
    if (empty($voucherCode)) {
      $form_state
        ->setErrorByName(self::VOUCHER_CODE_FIELD, $this
        ->t('Invalid voucher code'));
      return;
    }
    if ($voucherCode
      ->isExpired()) {
      $form_state
        ->setErrorByName(self::VOUCHER_CODE_FIELD, $this
        ->t('This voucher code is no longer valid'));
      return;
    }

    // Set the entity reference to match the voucher code input.
    $form_state
      ->setValue(self::VOUCHER_REFERENCE_FIELD, [
      [
        'target_id' => $voucherCode
          ->id(),
      ],
    ]);
  }

  /**
   * Lookup the voucher entity that corresponds with a given code.
   *
   * @param string $code
   *   The voucher code.
   *
   * @return \Drupal\my_voucher_code\VoucherCodeInterface|null
   *   The voucher entity. Null if no entity exists for this
   *   code.
   */
  private function lookupVoucherCodeEntity($code) {
    if (empty($code)) {
      return NULL;
    }

    /** @var \Drupal\my_voucher\VoucherInterface[] $vouchers */
    $vouchers = $this->entityTypeManager
      ->getStorage('voucher')
      ->loadByProperties([
      'code' => trim($code),
    ]);
    return empty($vouchers) ? NULL : reset($vouchers);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ExampleCustomInput::$entityTypeManager protected property The entity type manager.
ExampleCustomInput::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
ExampleCustomInput::formElement public function Builds a renderable array for the field. Overrides ExtraFieldFormInterface::formElement
ExampleCustomInput::lookupVoucherCodeEntity private function Lookup the voucher entity that corresponds with a given code.
ExampleCustomInput::validateVoucherCode public function Field validation callback for voucher code.
ExampleCustomInput::VOUCHER_CODE_FIELD constant The name of the voucher code input field.
ExampleCustomInput::VOUCHER_REFERENCE_FIELD constant The name of the field that references a voucher code.
ExampleCustomInput::__construct public function ExampleCustomInput constructor. Overrides PluginBase::__construct
ExtraFieldFormBase::$entity protected property The field's parent entity.
ExtraFieldFormBase::$entityFormDisplay protected property The entity form display.
ExtraFieldFormBase::$formMode protected property The form mode.
ExtraFieldFormBase::getEntity public function Returns the field's parent entity. Overrides ExtraFieldFormInterface::getEntity
ExtraFieldFormBase::getEntityFormDisplay public function Returns the entity form display object of the field's host entity. Overrides ExtraFieldFormInterface::getEntityFormDisplay
ExtraFieldFormBase::getFormMode public function Returns the entity form mode of the field's host entity. Overrides ExtraFieldFormInterface::getFormMode
ExtraFieldFormBase::setEntity public function Stores the field's parent entity. Overrides ExtraFieldFormInterface::setEntity
ExtraFieldFormBase::setEntityFormDisplay public function Stores the entity form display. Overrides ExtraFieldFormInterface::setEntityFormDisplay
ExtraFieldFormBase::setFormMode public function Stores the entity form mode. Overrides ExtraFieldFormInterface::setFormMode
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.