1

I made the following module with a custom entity in it. enter image description here

This is all working fine, but now i want to make a entity reference field in some content type to this custom entity.

For this i made the ConfigurationSelection.php file which looks like this :

<?php

namespace Drupal\sg_configuration_rule\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;

/**
 * Provides specific access control for the comment entity type.
 *
 * @EntityReferenceSelection(
 *   id = "default:sg_configuration_selection",
 *   label = @Translation("Configuration Selections selection"),
 *   entity_types = {"configuration_rule"},
 *   group = "default",
 *   weight = 1
 * )
 */
class ConfigurationSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);

    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
    $rule = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);

    return $rule;
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableNewEntities(array $entities) {
    $entities = parent::validateReferenceableNewEntities($entities);

    return $entities;
  }

}

This custom entity is not found when want to select it when adding a reference field:

enter image description here

My entity itself looks like this:

<?php

namespace Drupal\sg_configuration_rule\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;

/**
 * Defines the Configuration rule entity.
 *
 * @ingroup sg_configuration_rule
 *
 * @ContentEntityType(
 *   id = "configuration_rule",
 *   label = @Translation("Configuration rule"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\sg_configuration_rule\ConfigurationRuleListBuilder",
 *     "views_data" = "Drupal\sg_configuration_rule\Entity\ConfigurationRuleViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\sg_configuration_rule\Form\ConfigurationRuleForm",
 *       "add" = "Drupal\sg_configuration_rule\Form\ConfigurationRuleForm",
 *       "edit" = "Drupal\sg_configuration_rule\Form\ConfigurationRuleForm",
 *       "delete" = "Drupal\sg_configuration_rule\Form\ConfigurationRuleDeleteForm",
 *     },
 *     "access" = "Drupal\sg_configuration_rule\ConfigurationRuleAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\sg_configuration_rule\ConfigurationRuleHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "configuration_rule",
 *   admin_permission = "administer configuration rule entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "name",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "langcode" = "langcode",
 *     "status" = "status",
 *   },
 *   links = {
 *     "canonical" = "/admin/stargazer/configuration_rule/{configuration_rule}",
 *     "add-form" = "/admin/stargazer/configuration_rule/add",
 *     "edit-form" = "/admin/stargazer/configuration_rule/{configuration_rule}/edit",
 *     "delete-form" = "/admin/stargazer/configuration_rule/{configuration_rule}/delete",
 *     "collection" = "/admin/stargazer/configuration_rule",
 *   },
 *   field_ui_base_route = "configuration_rule.settings"
 * )
 */
class ConfigurationRule extends ContentEntityBase implements ConfigurationRuleInterface {

  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += [
      'user_id' => \Drupal::currentUser()->id(),
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public function setName($name) {
    $this->set('name', $name);
    return $this;
  }

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

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@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}
   */
  public function isPublished() {
    return (bool) $this->getEntityKey('status');
  }

  /**
   * {@inheritdoc}
   */
  public function setPublished($published) {
    $this->set('status', $published ? TRUE : FALSE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginType() {
    $baseApiPluginManager = \Drupal::service('plugin.manager.base_api_plugin');
    return $baseApiPluginManager->createInstance($this->get('plugin_type')->value);
  }

  /**
   * {@inheritdoc}
   */
  public function setPluginType($plugin_type) {
    $this->set('plugin_type', $plugin_type);
    return $this;
  }

  /**
   * Get the server node.
   *
   * @return \Drupal\node\Entity\Node
   *   The server node as object.
   */
  public function getServerNode() {
    return $this->get('server_node')->first()->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function setServerNode($server_node_id) {
    $this->set('server_node', $server_node_id);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfig() {
    return $this->get('configuration')->first()->getValue();
  }

  /**
   * {@inheritdoc}
   */
  public function setConfig($config) {
    $this->set('configuration', $config);
    return $this;
  }

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

  /**
   * {@inheritdoc}
   */
  public function setHash($hash) {
    $this->set('hash', $hash);
    return $this;
  }

  /**
   * {@inheritdoc}
   *
   * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Configuration rule entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of the Configuration rule entity.'))
      ->setSettings([
        'max_length' => 50,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

    $fields['plugin_type'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Plugin'))
      ->setDescription(t('The plugin type of the Configuration rule entity.'))
      ->setSettings([
        'max_length' => 255,
        'text_processing' => 0,
      ])
      ->setDefaultValue('')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'string',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -4,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

    $fields['server_node'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Server node'))
      ->setDescription(t('The server node linked to the Configuration rule entity.'))
      ->setSetting('target_type', 'node')
      ->setSetting('handler', 'default')
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'node',
        'weight' => -4,
      ])
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

    $fields['configuration'] = BaseFieldDefinition::create('map')
      ->setLabel(t('Configuration'))
      ->setDescription(t('The custom configuration of the Configuration rule entity.'))
      ->setDisplayConfigurable('form', FALSE)
      ->setDisplayConfigurable('view', FALSE)
      ->setRequired(FALSE);

    $intervals = [
      60,
      900,
      1800,
      3600,
      7200,
      10800,
      21600,
      32400,
      43200,
      64800,
      86400,
      172800,
      259200,
    ];
    $period = array_map([
      \Drupal::service('date.formatter'),
      'formatInterval',
    ], array_combine($intervals, $intervals));
    $period[0] = t('Never');

    $fields['cron_settings'] = BaseFieldDefinition::create('list_integer')
      ->setLabel(t('Run every'))
      ->setDescription(t('The length of time between each cron run for this single job.'))
      ->setDefaultValue(3600)
      ->setSetting('unsigned', TRUE)
      ->setRequired(TRUE)
      ->setSetting('allowed_values', $period)
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 80,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['status'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Publishing status'))
      ->setDescription(t('An indication whether the Configuration rule is active.'))
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => 99,
      ]);

    $fields['hash'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Identification hash'))
      ->setDescription(t('The unique has of the Configuration rule entity.'))
      ->setSettings([
        'max_length' => 255,
        'text_processing' => 0,
      ])
      ->setDefaultValue('');

    $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;
  }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.