getReferenceableEntities example


  protected static function matchEntityByTitle(SelectionInterface $handler$input, array &$element, FormStateInterface $form_state$strict) {
    $entities_by_bundle = $handler->getReferenceableEntities($input, '=', 6);
    $entities = array_reduce($entities_by_bundlefunction D$flattened$bundle_entities) {
      return $flattened + $bundle_entities;
    }[]);
    $params = [
      '%value' => $input,
      '@value' => $input,
      '@entity_type_plural' => \Drupal::entityTypeManager()->getDefinition($element['#target_type'])->getPluralLabel(),
    ];
    if (empty($entities)) {
      if ($strict) {
        // Error if there are no entities available for a required field.

  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    // Get all the workspace entities and sort them in tree order.     $storage = $this->entityTypeManager->getStorage('workspace');
    $workspace_tree = $this->workspaceRepository->loadTree();
    $entities = array_replace($workspace_tree$storage->loadMultiple());

    // If we need to restrict the list of workspaces by searching only a part of     // their label ($match) or by a number of results ($limit), the workspace     // tree would be mangled because it wouldn't contain all the tree items.     if ($match || $limit) {
      $options = parent::getReferenceableEntities($match$match_operator$limit);
    }
    else {
      $options = [];
      foreach ($entities as $entity) {
        $options[$entity->bundle()][$entity->id()] = str_repeat('-', $workspace_tree[$entity->id()]['depth']) . Html::escape($this->entityRepository->getTranslationFromContext($entity)->label());
      }
    }

    $restricted_access_entities = [];
    foreach ($options as $bundle => $bundle_options) {
      foreach (array_keys($bundle_options) as $id) {
        

    $this->createEntityReferenceField('entity_test', 'test_bundle', 'test_field', $this->randomString(), 'node', 'views', $handler_settings);
    $field_config = FieldConfig::loadByName('entity_test', 'test_bundle', 'test_field');
    $this->selectionHandler = $this->container->get('plugin.manager.entity_reference_selection')->getSelectionHandler($field_config);
  }

  /** * Tests the selection handler. */
  public function testSelectionHandler() {
    // Tests the selection handler.     $this->assertResults($this->selectionHandler->getReferenceableEntities());

    // Add a relationship to the view.     $view = Views::getView('test_entity_reference');
    $view->setDisplay();
    $view->displayHandlers->get('default')->setOption('relationships', [
      'test_relationship' => [
        'id' => 'uid',
        'table' => 'node_field_data',
        'field' => 'uid',
      ],
    ]);

    
'direction' => 'asc',
      ],
    ]);

    // The $own_permission_user should only be allowed to reference 'top1' and     // 'child1_1'.     $this->setCurrentUser($own_permission_user);
    $expected = [
      'top1',
      'child1_1',
    ];
    $this->assertEquals($expectedarray_keys($selection_handler->getReferenceableEntities()['workspace']));
    $this->assertEquals($expectedarray_keys($selection_handler->getReferenceableEntities(NULL, 'CONTAINS', 3)['workspace']));
    $expected = [
      'top1',
    ];
    $this->assertEquals($expectedarray_keys($selection_handler->getReferenceableEntities('top')['workspace']));

    // The $any_permission_user and $admin_permission_user should be allowed to     // reference any workspace.     $expected_all = [
      'top1',
      'child1_1',
      
$options[$bundle][$entity_id] = Html::escape($this->entityRepository->getTranslationFromContext($entity)->label() ?? '');
      }
    }

    return $options;
  }

  /** * {@inheritdoc} */
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $options = $this->getReferenceableEntities($match$match_operator);
    return count($options, COUNT_RECURSIVE) - count($options);
  }

}

class PhpSelection extends DefaultSelection {

  /** * {@inheritdoc} */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    // No input, return everything from the entity query.     if ($match === NULL || $match === '') {
      return parent::getReferenceableEntities($match$match_operator$limit);
    }

    // Start with the selection results returned by the entity query. Don't use     // any limit because we have to apply a limit after filtering the items.     $options = parent::getReferenceableEntities($match$match_operator);

    // Always use a case-insensitive, escaped match. Entity labels returned by     // SelectionInterface::getReferenceableEntities() are already escaped, so     // the incoming $match needs to be escaped as well, making the comparison     // possible.     // @see \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface::getReferenceableEntities()
 + $field_definition->getSetting('handler_settings') ?: [];

    $entity_type = \Drupal::entityTypeManager()->getDefinition($options['target_type']);
    $options['sort'] = [
      'field' => $entity_type->getKey('id'),
      'direction' => 'DESC',
    ];
    $selection_handler = $manager->getInstance($options);

    // Select a random number of references between the last 50 referenceable     // entities created.     if ($referenceable = $selection_handler->getReferenceableEntities(NULL, 'CONTAINS', 50)) {
      $group = array_rand($referenceable);
      $values['target_id'] = array_rand($referenceable[$group]);
      return $values;
    }

    // Attempt to create a sample entity, avoiding recursion.     $entity_storage = \Drupal::entityTypeManager()->getStorage($options['target_type']);
    if ($entity_storage instanceof ContentEntityStorageInterface) {
      $bundle = static::getRandomBundle($entity_type$options);

      // Track the generated entity by reference type, target type, and bundle.
'handler_settings' => [
          // Restrict selection of terms to a single vocabulary.           'target_bundles' => [
            $vocabulary->id() => $vocabulary->id(),
          ],
        ],
      ],
    ]);
    $field->save();

    $handler = $this->container->get('plugin.manager.entity_reference_selection')->getSelectionHandler($field);
    $result = $handler->getReferenceableEntities();

    $expected_result = [
      $vocabulary->id() => [
        $term->id() => $term->getName(),
      ],
    ];

    $this->assertSame($expected_result$result, 'Terms selection restricted to a single vocabulary.');
  }

}
Xss::filter($this->renderer->renderPlain($results[$id])$allowed_tags)
      );
    }

    return $stripped_results;
  }

  /** * {@inheritdoc} */
  public function countReferenceableEntities($match = NULL, $match_operator = 'CONTAINS') {
    $this->getReferenceableEntities($match$match_operator);
    return $this->view->pager->getTotalItems();
  }

  /** * {@inheritdoc} */
  public function validateReferenceableEntities(array $ids) {
    $entities = $this->getDisplayExecutionResults(NULL, 'CONTAINS', 0, $ids);
    $result = [];
    if ($entities) {
      $result = array_keys($entities);
    }
'target_bundles' => NULL,
      // Add sorting.       'sort' => [
        'field' => 'field_text.value',
        'direction' => 'DESC',
      ],
    ];
    $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);

    // Not only assert the result, but make sure the keys are sorted as     // expected.     $result = $handler->getReferenceableEntities();
    $expected_result = [
      $nodes['published2']->id() => $node_labels['published2'],
      $nodes['published1']->id() => $node_labels['published1'],
    ];
    $this->assertSame($expected_result$result['article'], 'Query sorted by field returned expected values.');

    // Assert sort by base field.     $selection_options['sort'] = [
      'field' => 'nid',
      'direction' => 'ASC',
    ];
    
'handler' => 'views',
      'view' => [
        'view_name' => 'test_display_entity_reference',
        'display_name' => 'entity_reference_1',
      ],
    ];
    $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);

    $state = \Drupal::state();
    $this->assertNull($state->get('views_test_config.views_post_render_called'));
    $state->set('views_test_config.views_post_render_cache_tag', TRUE);
    $result = $handler->getReferenceableEntities();
    $this->assertCount(5, $result['entity_test']);
    $this->assertTrue($state->get('views_test_config.views_post_render_called'));
  }

}

  public function testReferenceablesWithNoLabelKey($match$match_operator$limit$count_limited, array $items$count_all) {
    // Test ::getReferenceableEntities().     $referenceables = $this->selectionHandler->getReferenceableEntities($match$match_operator$limit);

    // Number of returned items.     if (empty($count_limited)) {
      $this->assertArrayNotHasKey($this->bundle, $referenceables);
    }
    else {
      $this->assertCount($count_limited$referenceables[$this->bundle]);
    }

    // Test returned items.     foreach ($items as $item) {
      
$this->assertCount(2, $query->execute());
  }

  /** * Tests with no conditions set. * * @throws \Drupal\Core\Entity\EntityStorageException */
  public function testNoConditions() {
    $this->assertEquals(
      $this->expectations['block_reusable'],
      $this->selectionHandler->getReferenceableEntities()
    );

    $this->blockNonReusable->setReusable();
    $this->blockNonReusable->save();

    // Ensure that the block is now returned as a referenceable entity.     $this->assertEquals(
      $this->expectations['both_blocks'],
      $this->selectionHandler->getReferenceableEntities()
    );
  }

  
$options = $selection_settings + [
      'target_type' => $target_type,
      'handler' => $selection_handler,
    ];
    $handler = $this->selectionManager->getInstance($options);

    if (isset($string)) {
      // Get an array of matching entities.       $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
      $match_limit = isset($selection_settings['match_limit']) ? (int) $selection_settings['match_limit'] : 10;
      $entity_labels = $handler->getReferenceableEntities($string$match_operator$match_limit);

      // Loop through the entities and convert them into autocomplete output.       foreach ($entity_labels as $values) {
        foreach ($values as $entity_id => $label) {
          $key = "$label ($entity_id)";
          // Strip things like starting/trailing white spaces, line breaks and           // tags.           $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
          // Names containing commas or quotes must be wrapped in quotes.           $key = Tags::encode($key);
          $matches[] = ['value' => $key, 'label' => $label];
        }
    $form['sort']['#access'] = FALSE;

    return $form;

  }

  /** * {@inheritdoc} */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    if ($match || $limit) {
      return parent::getReferenceableEntities($match$match_operator$limit);
    }

    $options = [];

    $bundles = $this->entityTypeBundleInfo->getBundleInfo('taxonomy_term');
    $bundle_names = $this->getConfiguration()['target_bundles'] ?: array_keys($bundles);

    $has_admin_access = $this->currentUser->hasPermission('administer taxonomy');
    $unpublished_terms = [];
    foreach ($bundle_names as $bundle) {
      if ($vocabulary = Vocabulary::load($bundle)) {
        
Home | Imprint | This part of the site doesn't use cookies.