contacts_events-8.x-1.x-dev/modules/villages/src/Plugin/VillageGroupType/OrganisationGroup.php

modules/villages/src/Plugin/VillageGroupType/OrganisationGroup.php
<?php

namespace Drupal\contacts_events_villages\Plugin\VillageGroupType;

use Drupal\contacts_events_villages\Entity\VillageGroupInterface;
use Drupal\contacts_events_villages\Plugin\VillageGroupTypeBase;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\entity\BundleFieldDefinition;

/**
 * Village group type for villages linked with organisations.
 *
 * @VillageGroupType(
 *   id = "organisation",
 *   label = @Translation("Organisation"),
 *   description = @Translation("Village groups linked to organisation contacts."),
 * )
 */
class OrganisationGroup extends VillageGroupTypeBase {

  /**
   * {@inheritdoc}
   */
  public function buildFieldDefinitions() {
    $fields = parent::buildFieldDefinitions();

    $fields['organisation'] = BundleFieldDefinition::create('entity_reference')
      ->setLabel(t('Organisation'))
      ->setDescription(t('Start typing the name of your organisation to find it.'))
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'search_api')
      ->setSetting('handler_settings', [
        'index' => 'contacts_index',
        'conditions' => [['roles', 'crm_org']],
      ])
      ->setRequired(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 99,
      ])
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 99,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function form(EntityReferenceFieldItemListInterface $items) {
    $form = [];
    /** @var \Drupal\entity\BundleFieldDefinition[] $definitions */
    $definitions = $this->buildFieldDefinitions();

    $selection_settings = $definitions['organisation']->getSetting('handler_settings') + ['match_operator' => $definitions['organisation']->getSetting('match_operator')];
    $referenced_entities = $items->referencedEntities();

    // Check for a default entity and check it has the right bundle.
    if (!empty($referenced_entities)) {
      $group = $referenced_entities[0];
      if ($group->bundle() == $this->getPluginId()) {
        $default = $group->get('organisation')->entity;
      }
    }

    $form['organisation'] = [
      '#title' => $definitions['organisation']->getLabel(),
      '#description' => $definitions['organisation']->getDescription(),
      '#type' => 'entity_autocomplete',
      '#target_type' => $definitions['organisation']->getSetting('target_type'),
      '#selection_handler' => $definitions['organisation']->getSetting('handler'),
      '#selection_settings' => $selection_settings,
      '#validate_reference' => FALSE,
      '#field_parents' => ['organisation'],
      '#default_value' => $default ?? NULL,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validate(array &$element, FormStateInterface $form_state, array &$complete_form) {
    if (!$form_state->hasValue($element['organisation']['#parents'])) {
      $form_state->setError($element['organisation'], new TranslatableMarkup('Please select an organisation to camp with.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildFormEntity(array $values, VillageGroupInterface $group) : VillageGroupInterface {
    $group = parent::buildFormEntity($values, $group);

    // Update the group name from the organisation if different.
    if (!empty($values['organisation'])) {
      $user_storage = $this->entityTypeManager->getStorage('user');
      $organisation = $user_storage->load($values['organisation']);

      if ($organisation && $group->getName() !== $organisation->label()) {
        $group->setName($organisation->label());
      }
    }

    return $group;
  }

  /**
   * {@inheritdoc}
   */
  public function getExisting(VillageGroupInterface $group) : VillageGroupInterface {
    // @todo Find existing based on organisation entity not name.
    $storage = $this->entityTypeManager->getStorage('c_events_village_group');
    $query = $storage->getQuery()
      ->condition('event', $group->getEventId())
      ->condition('organisation', $group->get('organisation')->target_id)
      ->sort('name', 'ASC');
    $query->accessCheck(TRUE);

    $result = $storage->loadMultiple($query->execute());
    return !empty($result) ? reset($result) : $group;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc