crm_core-8.x-3.x-dev/modules/crm_core_contact/src/Entity/Individual.php

modules/crm_core_contact/src/Entity/Individual.php
<?php

namespace Drupal\crm_core_contact\Entity;

use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\crm_core_contact\IndividualInterface;
use Drupal\entity\Revision\RevisionableContentEntityBase;
use Drupal\user\EntityOwnerTrait;

/**
 * CRM Individual Entity Class.
 *
 * @ContentEntityType(
 *   id = "crm_core_individual",
 *   label = @Translation("Individual"),
 *   bundle_label = @Translation("Individual type"),
 *   handlers = {
 *     "access" = "Drupal\crm_core_contact\IndividualAccessControlHandler",
 *     "form" = {
 *       "default" = "Drupal\crm_core_contact\Form\IndividualForm",
 *       "delete" = "Drupal\crm_core_contact\Form\ContactDeleteForm",
 *     },
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\crm_core_contact\IndividualListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",
 *       "revision" = "\Drupal\entity\Routing\RevisionRouteProvider",
 *     },
 *     "local_task_provider" = {
 *       "default" = "\Drupal\crm_core_contact\Menu\ContactLocalTaskProvider",
 *     },
 *   },
 *   show_revision_ui = TRUE,
 *   admin_permission = "administer crm_core_individual entities",
 *   base_table = "crm_core_individual",
 *   revision_table = "crm_core_individual_revision",
 *   entity_keys = {
 *     "id" = "individual_id",
 *     "revision" = "revision_id",
 *     "bundle" = "type",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode",
 *     "owner" = "uid",
 *     "published" = "status",
 *   },
 *   revision_metadata_keys = {
 *     "revision_user" = "revision_user",
 *     "revision_created" = "revision_created",
 *     "revision_log_message" = "revision_log_message",
 *   },
 *   bundle_entity_type = "crm_core_individual_type",
 *   field_ui_base_route = "entity.crm_core_individual_type.edit_form",
 *   permission_granularity = "bundle",
 *   permission_labels = {
 *     "singular" = @Translation("Individual"),
 *     "plural" = @Translation("Individuals"),
 *   },
 *   links = {
 *     "add-page" = "/crm-core/individual/add",
 *     "add-form" = "/crm-core/individual/add/{crm_core_individual_type}",
 *     "canonical" = "/crm-core/individual/{crm_core_individual}",
 *     "collection" = "/crm-core/individual",
 *     "edit-form" = "/crm-core/individual/{crm_core_individual}/edit",
 *     "delete-form" = "/crm-core/individual/{crm_core_individual}/delete",
 *     "revision" = "/crm-core/individual/{crm_core_individual}/revisions/{crm_core_individual_revision}/view",
 *     "revision-revert-form" = "/crm-core/individual/{crm_core_individual}/revisions/{crm_core_individual_revision}/revert",
 *     "version-history" = "/crm-core/individual/{crm_core_individual}/revisions",
 *   }
 * )
 */
class Individual extends RevisionableContentEntityBase implements EntityPublishedInterface, IndividualInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;
  use EntityPublishedTrait;
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);
    // Add the published field.
    $fields += static::publishedBaseFieldDefinitions($entity_type);

    $fields['uid']
      ->setLabel(t('Owned by'))
      ->setDescription(t('The username of the contact owner.'))
      ->setRevisionable(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'inline',
        'type' => 'author',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['status']->setLabel(t('Active'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => 1,
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the individual was created.'))
      ->setRevisionable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 5,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the individual was last edited.'))
      ->setRevisionable(TRUE);

    $fields['name'] = BaseFieldDefinition::create('name')
      ->setLabel(t('Name'))
      ->setDescription(t('Name of the individual.'))
      ->setRevisionable(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'name_default',
        'weight' => 0,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'name_default',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Label'))
      ->setRevisionable(TRUE)
      ->setDisplayOptions('form', [
        'region' => 'hidden',
        'weight' => -20,
      ])
      ->setDisplayOptions('view', [
        'label' => 'string',
        'region' => 'hidden',
      ]);

    return $fields;
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

    foreach (array_keys($this->getTranslationLanguages()) as $langcode) {
      $translation = $this->getTranslation($langcode);

      // If no owner has been set explicitly, make the anonymous user the owner.
      if (!$translation->getOwner()) {
        $translation->setOwnerId(0);
      }
    }

    // If no revision owner has been set explicitly, make the individual owner
    // the revision owner.
    if (!$this->getRevisionUser()) {
      $this->setRevisionUserId($this->getOwnerId());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save() {
    $this->saveLabel();

    return parent::save();
  }

  /**
   * Sets the Individual's label from the name.
   */
  protected function saveLabel() {
    $name_array = [];
    $name_formatter = \Drupal::service('name.formatter');

    $type = IndividualType::load($this->bundle());
    $component_layout = 'default';
    $formatted_name = NULL;

    if ($this->name[0] != NULL) {
      $name_array = $this->name[0]->getValue();
      // Prevent literal "_none" value saved for select fields.
      // Adopted from https://www.drupal.org/i/3491471 .
      // @todo Remove once #3491471 is released.
      array_walk($name_array, function (&$value) {
        if ($value === '_none') {
          $value = '';
        }
      });
      $formatted_name = (string) $name_formatter->format($name_array, $component_layout);
    }

    if (empty($formatted_name)) {
      if (!$id = $this->id()) {
        $id = $this->generateRandomString();
      }
      $name_array = [
        'Nameless',
        $type->label(),
        $id,
      ];
      $name_array = array_filter($name_array);
      $formatted_name = implode(' ', $name_array);
    }

    $this->label = $formatted_name;
  }

  /**
   * Generates a random string.
   *
   * The string is used when the Individual does not have a fullname.
   */
  protected function generateRandomString($length = 4) {
    $x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $ceil = ceil($length / 62);

    return substr(str_shuffle(str_repeat($x, $ceil)), 1, $length);
  }

  /**
   * Gets the primary address.
   *
   * @return \Drupal\Core\Field\FieldItemListInterface|\Drupal\Core\TypedData\TypedDataInterface
   *   The address property object.
   */
  public function getPrimaryAddress() {
    return $this->getPrimaryField('address');
  }

  /**
   * {@inheritdoc}
   */
  public function getPrimaryEmail() {
    return $this->getPrimaryField('email');
  }

  /**
   * {@inheritdoc}
   */
  public function getPrimaryPhone() {
    return $this->getPrimaryField('phone');
  }

  /**
   * Gets the primary field.
   *
   * @param string $field
   *   The primary field name.
   *
   * @return \Drupal\Core\Field\FieldItemListInterface|\Drupal\Core\TypedData\TypedDataInterface
   *   The primary field property object.
   *
   * @throws \InvalidArgumentException
   *   If no primary field is configured.
   *   If the configured primary field does not exist.
   */
  public function getPrimaryField($field) {
    $type = $this->get('type')->entity;
    $name = empty($type->primary_fields[$field]) ? '' : $type->primary_fields[$field];
    return $this->get($name);
  }

}

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

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