/** * {@inheritdoc} */ public function getDerivativeDefinitions($base_plugin_definition) { $nodes = $this->nodeStorage->loadByProperties(['type' => 'article']); foreach ($nodes as $node) { $this->derivatives[$node->id()] = $base_plugin_definition; $this->derivatives[$node->id()]['admin_label'] = t('Node block: ') . $node->label(); } return $this->derivatives; }
/** * {@inheritdoc} */ public function getVisibleBlocksPerRegion(array &$cacheable_metadata = []) { $active_theme = $this->themeManager->getActiveTheme(); // Build an array of the region names in the right order. $empty = array_fill_keys($active_theme->getRegions(), array()); $full = array(); foreach ($this->blockStorage->loadByProperties(array('theme' => $active_theme->getName())) as $block_id => $block) { /** @var \Drupal\block\BlockInterface $block */ $access = $block->access('view', NULL, TRUE); $region = $block->getRegion(); if (!isset($cacheable_metadata[$region])) { $cacheable_metadata[$region] = CacheableMetadata::createFromObject($access); } else { $cacheable_metadata[$region] = $cacheable_metadata[$region]->merge(CacheableMetadata::createFromObject($access)); } // Set the contexts on the block before checking access. if ($access->isAllowed()) { $full[$region][$block_id] = $block; } } // Merge it with the actual values to maintain the region ordering. $assignments = array_intersect_key(array_merge($empty, $full), $empty); foreach ($assignments as &$assignment) { // Suppress errors because PHPUnit will indirectly modify the contents, // triggering https://bugs.php.net/bug.php?id=50688. @uasort($assignment, 'Drupal\\block\\Entity\\Block::sort'); } return $assignments; }
/** * Validates the id field. */ public function validateId(array $element, FormStateInterface $form_state, array $form) { $taxType = $this->getEntity(); $id = $element['#value']; if (!preg_match('/[a-z_]+/', $id)) { $form_state->setError($element, $this->t('The machine name must be in lowercase, underscore-separated letters only.')); } elseif ($taxType->isNew()) { $loadedTaxTypes = $this->taxTypeStorage->loadByProperties(['id' => $id]); if ($loadedTaxTypes) { $form_state->setError($element, $this->t('The machine name is already in use.')); } } }
/** * Validates the numeric code. */ public function validateNumericCode(array $element, FormStateInterface &$form_state, array $form) { $currency = $this->getEntity(); $numeric_code = $element['#value']; if ($numeric_code && !preg_match('/^\\d{3}$/i', $numeric_code)) { $form_state->setError($element, $this->t('The numeric code must consist of three digits.')); } elseif ($currency->isNew()) { $loaded_currencies = $this->storage->loadByProperties(['numericCode' => $numeric_code]); if ($loaded_currencies) { $form_state->setError($element, $this->t('The numeric code is already in use.')); } } }
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { if ($this->entity->isNew()) { $exists = $this->blockContentStorage->loadByProperties(array('info' => $form_state->getValue(['info', 0, 'value']))); if (!empty($exists)) { $form_state->setErrorByName('info', $this->t('A block with description %name already exists.', array('%name' => $form_state->getValue(array('info', 0, 'value'))))); } } }
/** * {@inheritdoc} */ public function validateForm(array &$form, array &$form_state) { if ($this->entity->isNew()) { $exists = $this->blockContentStorage->loadByProperties(array('info' => $form_state['values']['info'])); if (!empty($exists)) { $this->setFormError('info', $form_state, $this->t('A block with description %name already exists.', array('%name' => $form_state['values']['info'][0]['value']))); } } }
/** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form['paragraphs_type'] = ['#type' => 'select', '#title' => $this->t('Paragraphs type'), '#required' => TRUE, '#options' => array_map(function (EntityInterface $paragraphs_type) { return $paragraphs_type->label(); }, $this->paragraphsTypeStorage->loadMultiple()), '#default_value' => $this->configuration['paragraphs_type']]; // Load and filter field configs to create options. /** @var \Drupal\field\FieldConfigInterface[] $field_configs */ $field_configs = $this->fieldConfigStorage->loadByProperties(['entity_type' => 'paragraph', 'bundle' => $this->configuration['paragraphs_type']]); $field_options = []; foreach ($field_configs as $field_config) { if (in_array($field_config->getType(), ['text', 'text_long', 'text_with_summary'])) { $field_options[$field_config->getName()] = $field_config->label(); } } $form['paragraph_field'] = ['#type' => 'select', '#title' => $this->t('Paragraph field'), '#description' => $this->t('<strong>Note:</strong> Field options do not appear until a type has been chosen and saved.'), '#options' => $field_options]; $form = parent::buildConfigurationForm($form, $form_state); return $form; }
/** * Disables the language switcher blocks. * * @param array $language_types * An array containing all language types whose language switchers need to * be disabled. */ protected function disableLanguageSwitcher(array $language_types) { $theme = $this->themeHandler->getDefault(); $blocks = $this->blockStorage->loadByProperties(array('theme' => $theme)); foreach ($language_types as $language_type) { foreach ($blocks as $block) { if (strpos($block->id, 'language_switcher_' . substr($language_type, 9)) !== FALSE) { $block->delete(); } } } }
/** * {@inheritdoc} */ public function getVisibleBlocksPerRegion(array $contexts) { // Build an array of the region names in the right order. $empty = array_fill_keys(array_keys($this->getRegionNames()), array()); $full = array(); foreach ($this->blockStorage->loadByProperties(array('theme' => $this->getTheme())) as $block_id => $block) { /** @var \Drupal\block\BlockInterface $block */ // Set the contexts on the block before checking access. if ($block->setContexts($contexts)->access('view')) { $full[$block->getRegion()][$block_id] = $block; } } // Merge it with the actual values to maintain the region ordering. $assignments = array_intersect_key(array_merge($empty, $full), $empty); foreach ($assignments as &$assignment) { // Suppress errors because PHPUnit will indirectly modify the contents, // triggering https://bugs.php.net/bug.php?id=50688. @uasort($assignment, 'Drupal\\block\\Entity\\Block::sort'); } return $assignments; }
/** * Disables the language switcher blocks. * * @param array $language_types * An array containing all language types whose language switchers need to * be disabled. */ protected function disableLanguageSwitcher(array $language_types) { $theme = $this->themeHandler->getDefault(); $blocks = $this->blockStorage->loadByProperties(array('theme' => $theme)); foreach ($language_types as $language_type) { foreach ($blocks as $block) { if ($block->getPluginId() == 'language_block:' . $language_type) { $block->delete(); } } } }
/** * Validates that there is only one default per tax type. */ public function validateDefault(array $element, FormStateInterface $form_state, array $form) { $taxRate = $this->getEntity(); $default = $element['#value']; if ($default) { $loadedTaxRates = $this->taxRateStorage->loadByProperties(['type' => $form_state->getValue('type')]); foreach ($loadedTaxRates as $rate) { if ($rate->getId() !== $taxRate->getOriginalId() && $rate->isDefault()) { $form_state->setError($element, $this->t('Tax rate %label is already the default.', ['%label' => $rate->label()])); break; } } } }
/** * Implements #element_validate for the currency number element. */ public function validateCurrencyNumber(array $element, FormStateInterface $form_state, array $form) { $currency = $this->getEntity(); $currency_number = $element['#value']; if ($currency_number && !preg_match('/^\\d{3}$/i', $currency_number)) { $form_state->setError($element, $this->t('The currency number must be three digits.')); } elseif ($currency->isNew()) { $loaded_currencies = $this->currencyStorage->loadByProperties(array('currencyNumber' => $currency_number)); if ($loaded_currencies) { $loaded_currency = reset($loaded_currencies); $form_state->setError($element, $this->t('The currency number is already in use by @link.', array('@link' => $this->linkGenerator->generate($loaded_currency->label(), $loaded_currency->urlInfo('edit-form'))))); } } }
/** * {@inheritdoc} */ public function execute($entity = NULL) { if (empty($this->configuration['node'])) { $this->configuration['node'] = $entity; } $recipient = $this->token->replace($this->configuration['recipient'], $this->configuration); // If the recipient is a registered user with a language preference, use // the recipient's preferred language. Otherwise, use the system default // language. $recipient_accounts = $this->storage->loadByProperties(array('mail' => $recipient)); $recipient_account = reset($recipient_accounts); if ($recipient_account) { $langcode = $recipient_account->getPreferredLangcode(); } else { $langcode = language_default()->id; } $params = array('context' => $this->configuration); if (drupal_mail('system', 'action_send_email', $recipient, $langcode, $params)) { watchdog('action', 'Sent email to %recipient', array('%recipient' => $recipient)); } else { watchdog('error', 'Unable to send email to %recipient', array('%recipient' => $recipient)); } }
/** * Returns an array of regions and their block entities. * * @return array * The array is first keyed by region machine name, with the values * containing an array keyed by block ID, with block entities as the values. */ protected function getRegionAssignments() { // Build an array of the region names in the right order. $empty = array_fill_keys(array_keys($this->getRegionNames()), array()); $full = array(); foreach ($this->blockStorage->loadByProperties(array('theme' => $this->getTheme())) as $block_id => $block) { $full[$block->get('region')][$block_id] = $block; } // Merge it with the actual values to maintain the region ordering. $assignments = array_intersect_key(array_merge($empty, $full), $empty); foreach ($assignments as &$assignment) { // Suppress errors because PHPUnit will indirectly modify the contents, // triggering https://bugs.php.net/bug.php?id=50688. @uasort($assignment, 'Drupal\\block\\Entity\\Block::sort'); } return $assignments; }
/** * Switches to a different user. * * We don't call session_save_session() because we really want to change users. * Usually unsafe! * * @param string $name * The username to switch to, or NULL to log out. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * A redirect response object. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ public function switchUser($name = NULL) { if (empty($name) || !($account = $this->userStorage->loadByProperties(['name' => $name]))) { throw new AccessDeniedHttpException(); } $account = reset($account); // Call logout hooks when switching from original user. $this->moduleHandler->invokeAll('user_logout', [$this->account]); // Regenerate the session ID to prevent against session fixation attacks. $this->sessionManager->regenerate(); // Based off masquarade module as: // https://www.drupal.org/node/218104 doesn't stick and instead only // keeps context until redirect. $this->account->setAccount($account); $this->session->set('uid', $account->id()); // Call all login hooks when switching to masquerading user. $this->moduleHandler->invokeAll('user_login', [$account]); return $this->redirect('<front>'); }
/** * {@inheritdoc} */ public function submit(array $form, array &$form_state) { $form_state['redirect_route'] = new Url('menu_ui.overview_page'); // Locked menus may not be deleted. if ($this->entity->isLocked()) { return; } // Reset all the menu links defined by the menu_link.static service. $result = \Drupal::entityQuery('menu_link')->condition('menu_name', $this->entity->id())->condition('module', '', '>')->condition('machine_name', '', '>')->sort('depth', 'ASC')->execute(); $menu_links = $this->storage->loadMultiple($result); foreach ($menu_links as $link) { $link->reset(); } // Delete all links to the overview page for this menu. $menu_links = $this->storage->loadByProperties(array('link_path' => 'admin/structure/menu/manage/' . $this->entity->id())); menu_link_delete_multiple(array_keys($menu_links)); // Delete the custom menu and all its menu links. $this->entity->delete(); $t_args = array('%title' => $this->entity->label()); drupal_set_message(t('The custom menu %title has been deleted.', $t_args)); watchdog('menu', 'Deleted custom menu %title and all its menu links.', $t_args, WATCHDOG_NOTICE); }
/** * {@inheritdoc} */ public function execute($entity = NULL) { if (empty($this->configuration['node'])) { $this->configuration['node'] = $entity; } $recipient = PlainTextOutput::renderFromHtml($this->token->replace($this->configuration['recipient'], $this->configuration)); // If the recipient is a registered user with a language preference, use // the recipient's preferred language. Otherwise, use the system default // language. $recipient_accounts = $this->storage->loadByProperties(array('mail' => $recipient)); $recipient_account = reset($recipient_accounts); if ($recipient_account) { $langcode = $recipient_account->getPreferredLangcode(); } else { $langcode = $this->languageManager->getDefaultLanguage()->getId(); } $params = array('context' => $this->configuration); if ($this->mailManager->mail('system', 'action_send_email', $recipient, $langcode, $params)) { $this->logger->notice('Sent email to %recipient', array('%recipient' => $recipient)); } else { $this->logger->error('Unable to send email to %recipient', array('%recipient' => $recipient)); } }
/** * A reverse lookup of a taxonomy term menus by vocabulary. * * @return \Drupal\taxonomy_menu\TaxonomyMenuInterface[] */ public function getTermMenusByVocabulary($vid) { return $this->menuStorage->loadByProperties(['vocabulary' => $vid]); }