/** * Say hello to the world. * * @return string * Return "Hello world!" string. */ public function helloWorld(EntityViewModeInterface $viewmode) { $content = ['#type' => 'markup', '#markup' => $this->t('Hello world!')]; // Second version displaying the opening hours of the library. $opening_hours = $this->config('happy_alexandrie.library_config')->get('opening_hours'); if (!empty($opening_hours)) { $content = ['#markup' => $this->t('<p>Greetings dear adventurer!</p><p>Opening hours:<br />@opening_hours</p>', array('@opening_hours' => $opening_hours))]; } // Third version with the query // Query against our entities. $query = $this->query_factory->get('node')->condition('status', 1)->condition('type', 'alexandrie_book')->condition('changed', REQUEST_TIME, '<')->range(0, 5); $nids = $query->execute(); if ($nids) { // Load the storage manager of our entity. $storage = $this->entity_manager->getStorage('node'); // Now we can load the entities. $nodes = $storage->loadMultiple($nids); list($entity_type, $viewmode_name) = explode('.', $viewmode->getOriginalId()); // Get the EntityViewBuilder instance. $render_controller = $this->entity_manager->getViewBuilder('node'); $build = $render_controller->viewMultiple($nodes, $viewmode_name); $build['#markup'] = $this->t('Happy Query by view mode: @label', array('@label' => $viewmode->label())); $content[] = $build; } else { $content[] = array('#markup' => $this->t('No result')); } return $content; }
/** * {inheritdoc} */ protected function getTitles($idList) { $ret = []; foreach ($this->entityManager->getStorage('node')->load($idList) as $node) { $ret[$node->nid] = entity_label('node', $node); } return $ret; }
/** * Tests the clearCachedDefinitions() method. * * @covers ::clearCachedDefinitions */ public function testClearCachedDefinitions() { $this->entityTypeManager->clearCachedDefinitions()->shouldBeCalled(); $this->entityTypeRepository->clearCachedDefinitions()->shouldBeCalled(); $this->entityTypeBundleInfo->clearCachedBundles()->shouldBeCalled(); $this->entityFieldManager->clearCachedFieldDefinitions()->shouldBeCalled(); $this->entityManager->clearCachedDefinitions(); }
/** * {@inheritdoc} */ public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { $id_parts = explode("/", $value); $entity = $this->entityTypeManager->getDefinition($id_parts[0], FALSE); if ($entity == NULL) { // Or maybe migrate comments some other way. throw new MigrateSkipRowException(); } return $id_parts[0]; }
/** * Test resolve() when a UUID corresponds to an entity. */ public function testResolveWithEntity() { $uuid = '392eab92-35c2-4625-872d-a9dab4da008e'; $entity = $this->getMock('Drupal\\Core\\Entity\\EntityInterface'); $entity->expects($this->once())->method('id')->will($this->returnValue(1)); $this->entityManager->expects($this->once())->method('loadEntityByUuid')->with('test_type', $uuid)->will($this->returnValue($entity)); $normalizer = $this->getMock('Drupal\\serialization\\EntityResolver\\UuidReferenceInterface'); $normalizer->expects($this->once())->method('getUuid')->with(array())->will($this->returnValue($uuid)); $this->assertSame(1, $this->resolver->resolve($normalizer, array(), 'test_type')); }
/** * {@inheritdoc} */ public function getDerivativeDefinitions(array $base_plugin_definition) { foreach ($this->entityManager->getDefinitions() as $entity_type => $entity_info) { // Only show content entities for now. if (!$entity_info->isSubclassOf('Drupal\\Core\\Config\\Entity\\ConfigEntityInterface')) { $this->derivatives[$entity_type] = $base_plugin_definition; $this->derivatives[$entity_type]['title'] = $entity_info->getLabel(); $this->derivatives[$entity_type]['entity type'] = $entity_type; } } $this->sortDerivatives(); return $this->derivatives; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // Get the custom entity ID. $custom_entity_id = $this->entity->getEntityType()->getBundleOf(); // Get the bundle key for the custom entity type. $custom_entity_bundle_key = $this->entityManager->getDefinition($custom_entity_id)->getKey('bundle'); $entities = $this->queryFactory->get($custom_entity_id)->condition($custom_entity_bundle_key, $this->entity->id())->execute(); if (!empty($entities)) { $caption = '<p>' . $this->formatPlural(count($entities), '%label is used by 1 entity on your site. You can not remove this entity type until you have removed all of the %label entities.', '%label is used by @count entities on your site. You may not remove %label until you have removed all of the %label entities.', ['%label' => $this->entity->label()]) . '</p>'; $form['description'] = array('#markup' => $caption); return $form; } else { return parent::buildForm($form, $form_state); } }
/** * {@inheritdoc} */ public function build() { // If the page is not a solution page, return an empty form so that the // rendering of this block can be omitted. if (empty($this->solution) || $this->solution->bundle() != 'solution') { return []; } // Get news referencing to this solution. // @todo EntityManager is deprecated. Use EntityTypeManager instead. // @see https://webgate.ec.europa.eu/CITnet/jira/browse/ISAICP-2669 $entities = $this->entityManager->getStorage('node')->loadByProperties([OgGroupAudienceHelperInterface::DEFAULT_FIELD => $this->solution->id()]); $items = []; foreach ($entities as $entity) { $items[] = ['#markup' => $entity->link()]; } // Also retrieve related collections. $ids = $this->entityManager->getStorage('rdf_entity')->getQuery()->condition('field_ar_affiliates', $this->solution->id())->execute(); $entities = Rdf::loadMultiple($ids); foreach ($entities as $entity) { $items[] = ['#markup' => $entity->link()]; } // Build the array output. if ($items) { return ['list' => ['#theme' => 'item_list', '#items' => $items, '#cache' => ['tags' => ['entity:node:news', 'entity:rdf_entity:collection']]]]; } return []; }
/** * Update a field. This is used to process fields when the storage * configuration changes. * * @param $entity_type * @param $field_name * @param string $op (encrypt / decrypt) */ protected function update_stored_field($entity_type, $field_name, $op = 'encrypt') { /** * Before we load entities, we have to disable the encryption setting. * Otherwise, the act of loading the entity triggers an improper decryption * Which messes up the batch encryption. */ $this->updatingStoredField = $field_name; /** * @var $query \Drupal\Core\Entity\Query\QueryInterface */ $query = $this->queryFactory->get($entity_type); // The field is present. $query->exists($field_name); $query->allRevisions(); $entity_ids = $query->execute(); // Load entities. /** * @var $entity_storage \Drupal\Core\Entity\ContentEntityStorageBase */ $entity_storage = $this->entityManager->getStorage($entity_type); foreach ($entity_ids as $revision_id => $entity_id) { /** * @var $entity \Drupal\Core\Entity\Entity */ $entity = $entity_storage->loadRevision($revision_id); /** * @var $field \Drupal\Core\Field\FieldItemList */ $field = $entity->get($field_name); $this->process_field($field, $op, TRUE); // Save the entity. $entity->save(); } }
/** * Gets the currently wrapped account * * @return AccountInterface */ public function getAccount() { if (!$this->account) { if ($this->originalAccount && $this->originalAccount->uid) { // Prey for Drupal being correctly initialized at this point $this->account = $this->entityManager->getStorage('user')->load($this->originalAccount->uid); } else { if ($this->originalAccount) { // User is not logged in, but we do have already a User // instance for anonymous user set $this->account = $this->originalAccount; } } } if (!$this->account instanceof AccountInterface) { // @todo why do the hell this happens only during unit tests? // seriously god I hate Drupal, and whatever is arround it $values = (array) $this->account; $this->account = new User(); foreach ($values as $key => $value) { $this->account->{$key} = $value; } } return $this->account; }
/** * {@inheritdoc} */ public function build() { $items = array(); // When on a node page, the parameter is already upcast as a node. $node = \Drupal::routeMatch()->getParameter('node'); if ($node) { // Read about entity query at http://www.sitepoint.com/drupal-8-version-entityfieldquery/. // See query API at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8. // The static method for using the query service would have been: // $query = \Drupal::entityQuery('node'); // Use injected queryFactory to look for items that are related // to the show that matches the input nid. $query = $this->entity_query->get('node')->condition('status', 1)->condition('type', 'tv_episode')->sort('field_related_season.entity.field_season_number.value', 'DESC')->sort('field_episode_number', 'DESC')->range(0, 5)->condition('field_related_season.entity.field_related_show.entity.nid', $node->id()); $nids = $query->execute(); // Note that entity_load() is deprecated. // The static method of loading the entity would have been: // \Drupal\node\Entity\Node::load(); // Use the injected entityManager to load the results into an array of node objects. $nodes = $this->entity_manager->getStorage('node')->loadMultiple($nids); foreach ($nodes as $node) { // Create a render array for each title field. // Note that field_view_field() is deprecated, use the view method on the field. $title = $node->title->view('full'); // Entities have a handy toLink() method. $items[] = $node->toLink($title); } } // Return a render array for a html list. return ['#theme' => 'item_list', '#items' => $items, '#cache' => ['contexts' => ['route']]]; }
/** * Creates the contact message entity without saving it. * * @return \Drupal\contact\Entity\Message|null * The contact message entity. NULL if the entity does not exist. */ protected function createContactMessage() { $contact_message = NULL; $contact_form = $this->getContactForm(); if ($contact_form) { $contact_message = $this->entityManager->getStorage('contact_message')->create(['contact_form' => $contact_form->id()]); } return $contact_message; }
/** * Returns the schema for the given table. * * @param string $table * The table name. * * @return array|bool * The table field mapping for the given table or FALSE if not available. */ protected function getTableMapping($table, $entity_type_id) { $storage = $this->entityManager->getStorage($entity_type_id); if ($storage instanceof SqlEntityStorageInterface) { $mapping = $storage->getTableMapping()->getAllColumns($table); } else { return FALSE; } return array_flip($mapping); }
/** * Checks if a field machine name is taken. * * @param string $value * The machine name, not prefixed. * @param array $element * An array containing the structure of the 'field_name' element. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @return bool * Whether or not the field machine name is taken. */ public function fieldNameExists($value, $element, FormStateInterface $form_state) { // Don't validate the case when an existing field has been selected. if ($form_state->getValue('existing_storage_name')) { return FALSE; } // Add the field prefix. $field_name = $this->configFactory->get('field_ui.settings')->get('field_prefix') . $value; $field_storage_definitions = $this->entityManager->getFieldStorageDefinitions($this->entityTypeId); return isset($field_storage_definitions[$field_name]); }
/** * check the possible node view modes and set with the given one. * * @param string $targetViewMode */ private function setViewMode($targetViewMode) { $view_modes = array_keys($this->entity_manager->getViewModeOptions('node')); if (in_array($targetViewMode, $view_modes)) { $this->configuration['block_node_view_mode'] = $targetViewMode; return; } // else update view_modes $this->view_modes = $this->entity_manager->getViewModeOptions('node'); $this->configuration['block_node_view_mode'] = $this->default_view_mode; }
/** * {@inheritdoc} */ protected function writeCache() { $data = array(); foreach ($this->entityManager->getDefinitions() as $entity_type_id => $entity_type) { $reflection = new \ReflectionClass($entity_type->getClass()); // We are only interested in importing content entities. if ($reflection->implementsInterface('\\Drupal\\Core\\Config\\Entity\\ConfigEntityInterface') || !$reflection->hasMethod('baseFieldDefinitions')) { continue; } foreach (array_keys($this->entityManager->getBundleInfo($entity_type_id)) as $bundle) { foreach ($this->entityManager->getFieldDefinitions($entity_type_id, $bundle) as $field_name => $field_details) { $relation_uri = $this->getRelationUri($entity_type_id, $bundle, $field_name); $data[$relation_uri] = array('entity_type' => $entity_type_id, 'bundle' => $bundle, 'field_name' => $field_name); } } } // These URIs only change when field info changes, so cache it permanently // and only clear it when field_info is cleared. $this->cache->set('rest:links:relations', $data, CacheBackendInterface::CACHE_PERMANENT, array('field_info')); }
/** * Returns the schema for the given table. * * @param string $table * The table name. * * @return array|bool * The table field mapping for the given table or FALSE if not available. */ protected function getTableMapping($table, $entity_type_id) { $storage = $this->entityManager->getStorage($entity_type_id); if ($storage instanceof SqlEntityStorageInterface) { $mapping = $storage->getTableMapping()->getAllColumns($table); } else { // @todo Stop calling drupal_get_schema() once menu links are converted // to the Entity Field API. See https://drupal.org/node/1842858. $schema = drupal_get_schema($table); $mapping = array_keys($schema['fields']); } return array_flip($mapping); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); // Mock the Config object, but methods will be mocked in the test class. $this->config = $this->getMockBuilder('\\Drupal\\Core\\Config\\ImmutableConfig')->disableOriginalConstructor()->getMock(); // Mock the ConfigFactory service. $this->configFactory = $this->getMockBuilder('\\Drupal\\Core\\Config\\ConfigFactory')->disableOriginalConstructor()->getMock(); $this->configFactory->expects($this->any())->method('get')->with('key.default_config')->willReturn($this->config); // Mock ConfigEntityStorage object, but methods will be mocked in the test // class. $this->configStorage = $this->getMockBuilder('\\Drupal\\Core\\Config\\Entity\\ConfigEntityStorage')->disableOriginalConstructor()->getMock(); // Mock EntityManager service. $this->entityManager = $this->getMockBuilder('\\Drupal\\Core\\Entity\\EntityManager')->disableOriginalConstructor()->getMock(); $this->entityManager->expects($this->any())->method('getStorage')->with('key')->willReturn($this->configStorage); // Create a dummy container. $this->container = new ContainerBuilder(); $this->container->set('entity.manager', $this->entityManager); $this->container->set('config.factory', $this->configFactory); // Each test class should call \Drupal::setContainer() in its own setUp // method so that test classes can add mocked services to the container // without affecting other test classes. }
/** * {@inheritdoc} */ protected function interact(InputInterface $input, OutputInterface $output) { $io = new DrupalStyle($input, $output); $config_types = $this->getConfigTypes(); $config_name = $input->getArgument('config-name'); if (!$config_name) { $config_type = $io->choiceNoList($this->trans('commands.config.export.single.questions.config-type'), array_keys($config_types), $this->trans('commands.config.export.single.options.simple-configuration')); $config_names = $this->getConfigNames($config_type); $config_name = $io->choiceNoList($this->trans('commands.config.export.single.questions.config-name'), array_keys($config_names)); if ($config_type !== 'system.simple') { $definition = $this->entityManager->getDefinition($config_type); $config_name = $definition->getConfigPrefix() . '.' . $config_name; } $input->setArgument('config-name', $config_name); } }
/** * Menu callback for Views tag autocompletion. * * Like other autocomplete functions, this function inspects the 'q' query * parameter for the string to use to search for suggestions. * * @return \Symfony\Component\HttpFoundation\JsonResponse * A JSON response containing the autocomplete suggestions for Views tags. */ public function autocompleteTag(Request $request) { $matches = array(); $string = $request->query->get('q'); // Get matches from default views. $views = $this->entityManager->getStorageController('view')->load(); foreach ($views as $view) { $tag = $view->get('tag'); if ($tag && strpos($tag, $string) === 0) { $matches[$tag] = $tag; if (count($matches) >= 10) { break; } } } return new JsonResponse($matches); }
/** * Get entity internal path * * @param string $type * Entity type * @param int|string $id * Entity identifier * * @return string * The Drupal internal path */ public function getEntityPath($type, $id) { // In most cases, this will be used for nodes only, so just set the // node URL. // It will avoid nasty bugs, since the 'text' core module does sanitize // (and call check_markup()) during field load if there are any circular // links dependencies between two nodes, it triggers an finite loop. // This will also make the whole faster. // @todo If node does not exists, no error will be triggered. if ('node' === $type) { return 'node/' . $id; } $entity = $this->entityManager->getStorage($type)->load($id); if (!$entity) { throw new \InvalidArgumentException(sprintf("entity of type %s with identifier %s does not exist", $type, $id)); } if (!$entity instanceof EntityInterface) { return $this->getDrupalEntityPath($type, $entity); } else { return $entity->url(); } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $field_key = '') { // Initialize field. $field = array(); // Fetch field if it already exists. if (!empty($field_key)) { $field = $this->config('ds.field.' . $field_key)->get(); } // Save the field for future reuse. $this->field = $field; $form['name'] = array( '#title' => t('Label'), '#type' => 'textfield', '#default_value' => isset($field['label']) ? $field['label'] : '', '#description' => t('The human-readable label of the field.'), '#maxlength' => 128, '#required' => TRUE, '#size' => 30, ); $form['id'] = array( '#type' => 'machine_name', '#default_value' => isset($field['id']) ? $field['id'] : '', '#maxlength' => 32, '#description' => t('The machine-readable name of this field. This name must contain only lowercase letters and underscores. This name must be unique.'), '#disabled' => !empty($field['id']), '#machine_name' => array( 'exists' => array($this, 'uniqueFieldName'), 'source' => array('name'), ), ); $entity_options = array(); $entities = $this->entityManager->getDefinitions(); foreach ($entities as $entity_type => $entity_info) { if ($entity_info->get('field_ui_base_route') || $entity_type == 'ds_views') { $entity_options[$entity_type] = Unicode::ucfirst(str_replace('_', ' ', $entity_type)); } } $form['entities'] = array( '#title' => t('Entities'), '#description' => t('Select the entities for which this field will be made available.'), '#type' => 'checkboxes', '#required' => TRUE, '#options' => $entity_options, '#default_value' => isset($field['entities']) ? $field['entities'] : array(), ); $form['ui_limit'] = array( '#title' => t('Limit field'), '#description' => t('Limit this field on field UI per bundles and/or view modes. The values are in the form of $bundle|$view_mode, where $view_mode may be either a view mode set to use custom settings, or \'default\'. You may use * to select all, e.g article|*, *|full or *|*. Enter one value per line.'), '#type' => 'textarea', '#default_value' => isset($field['ui_limit']) ? $field['ui_limit'] : '', ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), '#weight' => 100, ); return $form; }
/** * {@inheritdoc} */ public function getDescription() { return $this->entityManager->getStorage('taxonomy_term')->load($this->pluginDefinition['metadata']['taxonomy_term_id'])->getDescription(); }
/** * Constructs a new EventManager object. * * @param EntityManager $entity_manager * The entity manager. */ function __construct(EntityManager $entity_manager) { $this->eventTypeStorage = $entity_manager->getStorage('event_type'); }
/** * Constructs a DeleteMultiple form object. * * @param \Drupal\user\TempStoreFactory $temp_store_factory * The tempstore factory. * @param \Drupal\Core\Entity\EntityManager $manager * The entity manager. */ public function __construct(TempStoreFactory $temp_store_factory, EntityManager $manager) { $this->tempStoreFactory = $temp_store_factory; $this->storageController = $manager->getStorageController('feeds_feed'); }
/** * {@inheritdoc} */ public function build() { $form = $this->entity_manager->getStorage('contact_message')->create(array('contact_form' => $this->configuration['contact_form'])); if (!$form) { return ''; } $form = $this->entity_form_builder->getForm($form); return $form; }