vais_promos-1.0.0-beta2/src/Entity/VaisPromo.php

src/Entity/VaisPromo.php
<?php

namespace Drupal\vais_promos\Entity;

use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\user\UserInterface;
use Drupal\vais_promos\VaisPromoInterface;

/**
 * Defines the Vertex AI Search Promo entity.
 *
 * @ingroup vais_promos
 *
 * This is the main definition of the entity type. From it, an entityType is
 * derived. The most important properties in this example are listed below.
 *
 * id: The unique identifier of this entityType. It follows the pattern
 * 'moduleName_xyz' to avoid naming conflicts.
 *
 * label: Human readable name of the entity type.
 *
 * handlers: Handler classes are used for different tasks. You can use
 * standard handlers provided by D8 or build your own, most probably derived
 * from the standard class. In detail:
 *
 * - view_builder: we use the standard controller to view an instance. It is
 *   called when a route lists an '_entity_view' default for the entityType
 *   (see routing.yml for details. The view can be manipulated by using the
 *   standard drupal tools in the settings.
 *
 * - list_builder: We derive our own list builder class from the
 *   entityListBuilder to control the presentation.
 *   If there is a view available for this entity from the views module, it
 *   overrides the list builder. @todo: any view? naming convention?
 *
 * - form: We derive our own forms to add functionality like additional fields,
 *   redirects etc. These forms are called when the routing list an
 *   '_entity_form' default for the entityType. Depending on the suffix
 *   (.add/.edit/.delete) in the route, the correct form is called.
 *
 * - access: Our own accessController where we determine access rights based on
 *   permissions.
 *
 * More properties:
 *
 *  - base_table: Define the name of the table used to store the data. Make sure
 *    it is unique. The schema is automatically determined from the
 *    BaseFieldDefinitions below. The table is automatically created during
 *    installation.
 *
 *  - fieldable: Can additional fields be added to the entity via the GUI?
 *    Analog to content types.
 *
 *  - entity_keys: How to access the fields. Analog to 'nid' or 'uid'.
 *
 *  - links: Provide links to do standard tasks. The 'edit-form' and
 *    'delete-form' links are added to the list built by the
 *    entityListController. They will show up as action buttons in an additional
 *    column.
 *
 * There are many more properties to be used in an entity type definition. For
 * a complete overview, please refer to the '\Drupal\Core\Entity\EntityType'
 * class definition.
 *
 * The following construct is the actual definition of the entity type which
 * is read and cached. Don't forget to clear cache after changes.
 *
 * @ContentEntityType(
 *   id = "vais_promo",
 *   label = @Translation("Vertex AI Search Promo entity"),
 *   internal = TRUE,
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\vais_promos\VaisPromoListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "form" = {
 *       "add" = "Drupal\vais_promos\Form\VaisPromoForm",
 *       "edit" = "Drupal\vais_promos\Form\VaisPromoForm",
 *       "delete" = "Drupal\vais_promos\Form\VaisPromoDeleteForm",
 *     },
 *     "access" = "Drupal\vais_promos\VaisPromoAccessControlHandler",
 *   },
 *   base_table = "vais_promo",
 *   admin_permission = "administer search",
 *   fieldable = TRUE,
 *   entity_keys = {
 *     "id" = "pid",
 *     "label" = "promo_trigger",
 *     "uuid" = "uuid",
 *     "search_page" = "promo_search_page",
 *   },
 *   links = {
 *     "canonical" = "/vais_promo/{vais_promo}",
 *     "edit-form" = "/admin/content/vais_promo/{vais_promo}/edit",
 *     "delete-form" = "/admin/content/vais_promo/{vais_promo}/delete",
 *     "collection" = "/admin/content/vais_promo/list"
 *   },
 *   field_ui_base_route = "vais_promo.vais_promo_settings",
 * )
 *
 * The 'links' above are defined by their path. For core to find corresponding
 * route, the route name must follow the correct pattern:
 *
 * entity.<entity-name>.<link-name> (replace dashes with underscores)
 * Example: 'entity.vais_promo.canonical'
 *
 * See routing file above for the corresponding implementation
 *
 * The 'VaisPromo' class defines methods and fields for the vais_promo entity.
 *
 * Being derived from the ContentEntityBase class, we can override the methods
 * we want. In our case we want to provide access to the standard fields about
 * creation and changed time stamps.
 *
 * Our interface (see VaisPromoInterface) also exposes the EntityOwnerInterface.
 * This allows us to provide methods for setting and providing ownership
 * information.
 *
 * The most important part is the definitions of the field properties for this
 * entity type. These are of the same type as fields added through the GUI, but
 * they can be changed in code. In the definition we can define if the user with
 * the rights privileges can influence the presentation (view, edit) of each
 * field.
 */
class VaisPromo extends ContentEntityBase implements VaisPromoInterface {

  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   *
   * When a new entity instance is added, set the user_id entity reference to
   * the current user as the creator of the instance.
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()->id(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   *
   * Define the field properties here.
   *
   * Field name, type and size determine the table structure.
   *
   * In addition, we can define how the field and its content can be manipulated
   * in the GUI. The behaviour of the widgets used can be determined here.
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    $configFactory = \Drupal::configFactory();
    $vaisPromoSettings = $configFactory->get('vais_promos.entity_type_settings');

    // Standard field, used as unique if primary index.
    $fields['pid'] = BaseFieldDefinition::create('integer')
      ->setLabel(t('ID'))
      ->setDescription(t('The ID of the Promo entity.'))
      ->setReadOnly(TRUE);

    $searchPageRepo = \Drupal::service('search.search_page_repository');
    $searchPageOptions = [];
    $activeSearchPages = $searchPageRepo->getActiveSearchPages();
    foreach ($searchPageRepo->sortSearchPages($activeSearchPages) as $entity) {
      if ($entity->get('plugin') == 'vertex_ai_search') {
        $searchPageOptions[$entity->id()] = $entity->label();
      }
    }

    $fields['promo_search_page'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Vertex AI Search Page'))
      ->setDescription(t('The Vertex AI Search Page on which this Promotion will appear.'))
      ->setRequired(TRUE)
      ->setSettings([
        'allowed_values' => $searchPageOptions,
      ])
      ->setDisplayOptions('view', [
        'label' => 'visible',
        'type' => 'list_default',
        'weight' => -7,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => -7,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    if (count($searchPageOptions) == 1) {
      $fields['promo_search_page']->setDefaultValue(implode(",", array_keys($searchPageOptions)));
    }

    // Keywords that will trigger the promotion.
    $fields['promo_trigger'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Promotion Triggering Query'))
      ->setDescription(t('Comma-separated list of keywords that will trigger this promotion.'))
      ->setRequired(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
        'text_processing' => 0,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -6,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -6,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    // Standard field, unique outside of the scope of the current project.
    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The UUID of the Promo entity.'))
      ->setReadOnly(TRUE);

    // Specify the type of promoted result (content reference or external link).
    $fields['promo_type'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Promoted Result Type'))
      ->setDescription(t('The type of Promoted Result.'))
      ->setRequired(TRUE)
      ->setSettings([
        'allowed_values' => [
          'internal' => t('Internal'),
          'external' => t('External'),
        ],
      ])
      ->setDisplayOptions('view', [
        'label' => 'visible',
        'type' => 'list_default',
        'weight' => -5,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    // Reference to the node that will appear if promotion is triggered.
    $fields['promo_content'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Content Reference'))
      ->setDescription(t('Reference the promoted content.'))
      ->setSetting('target_type', 'node')
      ->setSetting('handler', 'default:node')
      ->setSetting('handler_settings', [
        'auto_create' => FALSE,
      ])
      ->setRequired(FALSE)
      ->setTranslatable(FALSE)
      ->setDisplayOptions('view', [
        'label' => 'visible',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => -4,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
        ],
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    // External link to which the promoted result is associated.
    $fields['promo_link'] = BaseFieldDefinition::create('string')
      ->setLabel(t('External Link'))
      ->setDescription(t('Provide the promoted result external link.'))
      ->setRequired(FALSE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
        'text_processing' => 0,
      ])
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    // When displaying the promo content on the SERP, override the node title.
    $fields['promo_title_override'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Promotion Title'))
      ->setDescription(t(
        'The displayed title of the promoted result.'
        ))
      ->setRequired(TRUE)
      ->setSettings([
        'default_value' => '',
        'max_length' => 255,
        'text_processing' => 0,
      ])
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -3,
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    // Description for the promo item to be displayed on SERP.
    $fields['promo_description'] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Promotion Description'))
      ->setDescription(t('Promotional copy displayed to end user.'))
      ->setDefaultValue('')
      ->setRequired(FALSE)
      ->setDisplayOptions('view', [
        'label' => 'visible',
        'type' => 'basic_string',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 0,
        'settings' => ['rows' => 4],
      ])
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayConfigurable('form', TRUE);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Demo entity entity.'))
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default');

    $fields['langcode'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Language code'))
      ->setDescription(t('The language code of Contact entity.'));

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

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

    return $fields;
  }

}

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

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