openquestions-1.0.x-dev/src/Entity/OqQuestion.php

src/Entity/OqQuestion.php
<?php

namespace Drupal\openquestions\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\openquestions\Model\OqQuestionInterface;
use Drupal\user\EntityOwnerTrait;
use Drupal\openquestions\Service\OQUtilsInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Defines the oq question entity class.
 *
 * @ContentEntityType(
 *   id = "oq_question",
 *   label = @Translation("OQ Question"),
 *   label_collection = @Translation("OQ Questions"),
 *   label_singular = @Translation("oq question"),
 *   label_plural = @Translation("oq questions"),
 *   label_count = @PluralTranslation(
 *     singular = "@count oq questions",
 *     plural = "@count oq questions",
 *   ),
 *   handlers = {
 *     "list_builder" = "Drupal\openquestions\List\OqQuestionListBuilder",
 *     "views_data" = "Drupal\views\EntityViewsData",
 *     "access" = "Drupal\openquestions\Access\OqQuestionAccessControlHandler",
 *     "form" = {
 *       "add" = "Drupal\openquestions\Form\OqQuestionForm",
 *       "edit" = "Drupal\openquestions\Form\OqQuestionForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",
 *     }
 *   },
 *   base_table = "oq_question",
 *   data_table = "oq_question_field_data",
 *   translatable = TRUE,
 *   admin_permission = "administer oq question",
 *   entity_keys = {
 *     "id" = "id",
 *     "langcode" = "langcode",
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "owner" = "uid",
 *   },
 *   links = {
 *     "collection" = "/admin/content/oq-question",
 *     "add-form" = "/oq-question/add",
 *     "canonical" = "/oq-question/{oq_question}",
 *     "edit-form" = "/oq-question/{oq_question}/edit",
 *     "delete-form" = "/oq-question/{oq_question}/delete",
 *   },
 *   field_ui_base_route = "entity.oq_question.settings",
 * )
 */
class OqQuestion extends ContentEntityBase implements OqQuestionInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;
  use StringTranslationTrait;

  /**
   * Our utils.
   *
   * @var \Drupal\openquestions\Service\OQUtilsInterface
   */
  protected $oqUtils;

  /**
   * Our logger.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * Overriden to get our services.
   */
  public function __construct(array $values, $entity_type, $bundle = FALSE, $translations = []) {
    parent::__construct($values, $entity_type, $bundle, $translations);

    // "Provide a method of DI for entities", https://www.drupal.org/project/drupal/issues/2142515
    $this->oqUtils = \Drupal::service('openquestions.oq_utils');
    $this->logger = \Drupal::service('openquestions.logger.channel.openquestions');
  }

  /**
   * {@inheritdoc}
   */
  public function getOptions() {
    $text = $this->get('options')->value;

    $ary = $this->oqUtils->parseStringList($text, ['LABEL']);
    if (!empty($ary['errors'])) {
      throw new \InvalidArgumentException($this->t('Invalid options: @msgs', ['@msgs' => implode(' ;; ', $ary['errors'])]));
    }

    return $this->oqUtils->stringListToOptions($ary['items']);
  }

  /**
   * {@inheritdoc}
   */
  public function getOptionsRangeInfo() {
    $options = $this->getOptions();
    $cc = count($options);

    $first = $cc > 0 ? array_pop($options) : NULL;
    $last = $cc > 1 ? array_shift($options) : NULL;

    $ret = [
      'first' => $first,
      'last' => $last,
      'type' => '',
    ];

    if ($cc == 2) {
      $ret['type'] = 'binary';
    }
    else if ($cc > 2) {
      $ret['type'] = 'range';
    }

    return $ret;
  }

  /**
   * {@inheritdoc}
   */
  public function getOptionName($optionValue) {
    $options = $this->getOptions();

    return array_key_exists($optionValue, $options) ? $options[$optionValue] : $this->t('Unknown');
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
    if (!$this->getOwnerId()) {
      // If no owner has been set explicitly, make the anonymous user the owner.
      $this->setOwnerId(0);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setTranslatable(TRUE)
      ->setLabel(t('Label'))
      ->setRequired(TRUE)
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'string',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Status'))
      ->setDefaultValue(TRUE)
      ->setSetting('on_label', 'Enabled')
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => FALSE,
        ],
        'weight' => 0,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'boolean',
        'label' => 'above',
        'weight' => 0,
        'settings' => [
          'format' => 'enabled-disabled',
        ],
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['description'] = BaseFieldDefinition::create('text_long')
      ->setTranslatable(TRUE)
      ->setLabel(t('Description'))
      ->setDisplayOptions('form', [
        'type' => 'text_textarea',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'type' => 'text_default',
        'label' => 'above',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setTranslatable(TRUE)
      ->setLabel(t('Author'))
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback(static::class . '::getDefaultEntityOwner')
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => 60,
          'placeholder' => '',
        ],
        'weight' => 15,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'author',
        'weight' => 15,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the oq question was created.'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'timestamp',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 20,
      ])
      ->setDisplayConfigurable('view', TRUE);

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

    $fields['options'] = BaseFieldDefinition::create('openquestions_question_options')
      ->setTranslatable(TRUE)
      ->setLabel(t('Options'))
      ->setDisplayOptions('form', [
        'type' => 'openquestions_question_options_widget',
        'weight' => 15,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'openquestions_question_options_formatter',
        'weight' => 15,
      ])
      ->setDisplayConfigurable('view', TRUE);

    $fields['locked_status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Locked'))
      ->setDefaultValue(FALSE);

    $fields['locked_date'] = BaseFieldDefinition::create('datetime')
      ->setLabel(t('Locked date'))
      ->setTranslatable(TRUE)
      ->setDescription(t('The time that the oq question was locked.'));

    $fields['locked_reason'] = BaseFieldDefinition::create('string')
      ->setTranslatable(TRUE)
      ->setLabel(t('Locked reason'))
      ->setSetting('max_length', 255);

    return $fields;
  }

}

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

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