InstrumentsWidget.php

PHOTO EMBED

Wed Jan 19 2022 14:52:39 GMT+0000 (Coordinated Universal Time)

Saved by @igor #drupal #php

<?php

namespace Drupal\musin_core\Plugin\Field\FieldWidget;

use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Custom field widget for instruments.
 *
 * @FieldWidget(
 *   id = "instruments_widget",
 *   label = @Translation("Instruments widget"),
 *   description = @Translation("Instruments widget"),
 *   field_types = {
 *     "entity_reference",
 *     "string"
 *   }
 * )
 */
class InstrumentsWidget extends WidgetBase {

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

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityTypeManager = $entityTypeManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    // TODO: Implement formElement() method.
    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $rows = [];
    $taxonomies = $this->entityTypeManager
      ->getStorage('taxonomy_term')
      ->loadByProperties([
        'vid' => 'instruments',
      ]);
    foreach ($taxonomies as $term) {
      $rows[$term->getName()] = $term->getName();
    }

    $element['first'] = [
      '#type' => 'checkboxes',
      '#options' => $rows,
      '#attributes' => [
        'name' => 'base_taxonomy',
      ]
    ];

    $element['second'] = [
      '#type' => 'textfield',
      '#title' => 'Enter your instruments',
      '#states' => [
        'visible' => [
          ':input[name="base_taxonomy"]' => ['value' => 'Other']
        ]
      ]
    ];

    return $element;
  }

}

content_copyCOPY