Example #1
1
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $forum_config = $this->config('forum.settings');
     $vid = $forum_config->get('vocabulary');
     $vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($vid);
     if (!$vocabulary) {
         throw new NotFoundHttpException();
     }
     // Build base taxonomy term overview.
     $form = parent::buildForm($form, $form_state, $vocabulary);
     foreach (Element::children($form['terms']) as $key) {
         if (isset($form['terms'][$key]['#term'])) {
             $term = $form['terms'][$key]['#term'];
             $form['terms'][$key]['term']['#url'] = Url::fromRoute('forum.page', ['taxonomy_term' => $term->id()]);
             unset($form['terms'][$key]['operations']['#links']['delete']);
             $route_parameters = $form['terms'][$key]['operations']['#links']['edit']['url']->getRouteParameters();
             if (!empty($term->forum_container->value)) {
                 $form['terms'][$key]['operations']['#links']['edit']['title'] = $this->t('edit container');
                 $form['terms'][$key]['operations']['#links']['edit']['url'] = Url::fromRoute('entity.taxonomy_term.forum_edit_container_form', $route_parameters);
             } else {
                 $form['terms'][$key]['operations']['#links']['edit']['title'] = $this->t('edit forum');
                 $form['terms'][$key]['operations']['#links']['edit']['url'] = Url::fromRoute('entity.taxonomy_term.forum_edit_form', $route_parameters);
             }
             // We don't want the redirect from the link so we can redirect the
             // delete action.
             unset($form['terms'][$key]['operations']['#links']['edit']['query']['destination']);
         }
     }
     // Remove the alphabetical reset.
     unset($form['actions']['reset_alphabetical']);
     // Use the existing taxonomy overview submit handler.
     $form['terms']['#empty'] = $this->t('No containers or forums available. <a href="@container">Add container</a> or <a href="@forum">Add forum</a>.', array('@container' => $this->url('forum.add_container'), '@forum' => $this->url('forum.add_forum')));
     return $form;
 }
 /**
  * Asserts page cache miss, then hit for the given URL; checks cache headers.
  *
  * @param \Drupal\Core\Url $url
  *   The URL to test.
  * @param string[] $expected_contexts
  *   The expected cache contexts for the given URL.
  * @param string[] $expected_tags
  *   The expected cache tags for the given URL.
  */
 protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
 {
     $absolute_url = $url->setAbsolute()->toString();
     sort($expected_contexts);
     sort($expected_tags);
     // Assert cache miss + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertCacheTags($expected_tags);
     $this->assertCacheContexts($expected_contexts);
     // Assert cache hit + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $this->assertCacheTags($expected_tags);
     $this->assertCacheContexts($expected_contexts);
     // Assert page cache item + expected cache tags.
     $cid_parts = array($url->setAbsolute()->toString(), 'html');
     $cid = implode(':', $cid_parts);
     $cache_entry = \Drupal::cache('render')->get($cid);
     sort($cache_entry->tags);
     $this->assertEqual($cache_entry->tags, $expected_tags);
     if ($cache_entry->tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getResponse()
 {
     if (!$this->response) {
         $this->response = new TrustedRedirectResponse($this->url->toString());
     }
     return $this->response;
 }
Example #4
0
 /**
  * {@inheritdoc}
  *
  * For anonymous users, the "active" class will be calculated on the server,
  * because most sites serve each anonymous user the same cached page anyway.
  * For authenticated users, the "active" class will be calculated on the
  * client (through JavaScript), only data- attributes are added to links to
  * prevent breaking the render cache. The JavaScript is added in
  * system_page_attachments().
  *
  * @see system_page_attachments()
  */
 public function generate($text, Url $url, $collect_cacheability_metadata = FALSE)
 {
     // Performance: avoid Url::toString() needing to retrieve the URL generator
     // service from the container.
     $url->setUrlGenerator($this->urlGenerator);
     // Start building a structured representation of our link to be altered later.
     $variables = array('text' => is_array($text) ? drupal_render($text) : $text, 'url' => $url, 'options' => $url->getOptions());
     // Merge in default options.
     $variables['options'] += array('attributes' => array(), 'query' => array(), 'language' => NULL, 'set_active_class' => FALSE, 'absolute' => FALSE);
     // Add a hreflang attribute if we know the language of this link's url and
     // hreflang has not already been set.
     if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {
         $variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();
     }
     // Set the "active" class if the 'set_active_class' option is not empty.
     if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {
         // Add a "data-drupal-link-query" attribute to let the
         // drupal.active-link library know the query in a standardized manner.
         if (!empty($variables['options']['query'])) {
             $query = $variables['options']['query'];
             ksort($query);
             $variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);
         }
         // Add a "data-drupal-link-system-path" attribute to let the
         // drupal.active-link library know the path in a standardized manner.
         if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {
             // @todo System path is deprecated - use the route name and parameters.
             $system_path = $url->getInternalPath();
             // Special case for the front page.
             $variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;
         }
     }
     // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
     // only when a quick strpos() gives suspicion tags are present.
     if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
         $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
     }
     // Allow other modules to modify the structure of the link.
     $this->moduleHandler->alter('link', $variables);
     // Move attributes out of options since generateFromRoute() doesn't need
     // them. Include a placeholder for the href.
     $attributes = array('href' => '') + $variables['options']['attributes'];
     unset($variables['options']['attributes']);
     $url->setOptions($variables['options']);
     if (!$collect_cacheability_metadata) {
         $url_string = $url->toString($collect_cacheability_metadata);
     } else {
         $generated_url = $url->toString($collect_cacheability_metadata);
         $url_string = $generated_url->getGeneratedUrl();
         $generated_link = GeneratedLink::createFromObject($generated_url);
     }
     // The result of the URL generator is a plain-text URL to use as the href
     // attribute, and it is escaped by \Drupal\Core\Template\Attribute.
     $attributes['href'] = $url_string;
     $result = SafeMarkup::format('<a@attributes>@text</a>', array('@attributes' => new Attribute($attributes), '@text' => $variables['text']));
     return $collect_cacheability_metadata ? $generated_link->setGeneratedLink($result) : $result;
 }
Example #5
0
 /**
  * Performs a HTTP request with Basic authentication.
  *
  * We do not use \Drupal\simpletest\WebTestBase::drupalGet because we need to
  * set curl settings for basic authentication.
  *
  * @param \Drupal\Core\Url $url
  *   A Url object.
  * @param string $username
  *   The user name to authenticate with.
  * @param string $password
  *   The password.
  * @param string $mime_type
  *   The MIME type for the Accept header.
  *
  * @return string
  *   Curl output.
  */
 protected function basicAuthGet(Url $url, $username, $password, $mime_type = NULL)
 {
     if (!isset($mime_type)) {
         $mime_type = $this->defaultMimeType;
     }
     $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $url->setAbsolute()->toString(), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $username . ':' . $password, CURLOPT_HTTPHEADER => array('Accept: ' . $mime_type)));
     $this->verbose('GET request to: ' . $url->toString() . '<hr />' . $out);
     return $out;
 }
Example #6
0
 /**
  * Submits the delete form.
  */
 public function deleteSubmit(array &$form, FormStateInterface $form_state)
 {
     $url = new Url('path.delete', array('pid' => $form_state->getValue('pid')));
     if ($this->getRequest()->query->has('destination')) {
         $url->setOption('query', $this->getDestinationArray());
         $this->getRequest()->query->remove('destination');
     }
     $form_state->setRedirectUrl($url);
 }
 /**
  * Tests bubbling of cacheable metadata for URLs.
  *
  * @param bool $collect_bubbleable_metadata
  *   Whether bubbleable metadata should be collected.
  * @param int $invocations
  *   The expected amount of invocations for the ::bubble() method.
  * @param array $options
  *   The URL options.
  *
  * @covers ::bubble
  *
  * @dataProvider providerUrlBubbleableMetadataBubbling
  */
 public function testUrlBubbleableMetadataBubbling($collect_bubbleable_metadata, $invocations, array $options)
 {
     $self = $this;
     $this->renderer->expects($this->exactly($invocations))->method('render')->willReturnCallback(function ($build) use($self) {
         $self->assertTrue(!empty($build['#cache']));
     });
     $url = new Url('test_1', [], $options);
     $url->setUrlGenerator($this->generator);
     $url->toString($collect_bubbleable_metadata);
 }
 /**
  * Asserts page cache miss, then hit for the given URL; checks cache headers.
  *
  * @param \Drupal\Core\Url $url
  *   The URL to test.
  * @param string[] $expected_contexts
  *   The expected cache contexts for the given URL.
  * @param string[] $expected_tags
  *   The expected cache tags for the given URL.
  */
 protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
 {
     $absolute_url = $url->setAbsolute()->toString();
     sort($expected_contexts);
     sort($expected_tags);
     $get_cache_header_values = function ($header_name) {
         $header_value = $this->drupalGetHeader($header_name);
         if (empty($header_value)) {
             return [];
         } else {
             return explode(' ', $header_value);
         }
     };
     // Assert cache miss + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
     $actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
     $this->assertIdentical($actual_contexts, $expected_contexts);
     if ($actual_contexts !== $expected_contexts) {
         debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
         debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
     }
     $this->assertIdentical($actual_tags, $expected_tags);
     if ($actual_tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
     }
     // Assert cache hit + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
     $actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertIdentical($actual_contexts, $expected_contexts);
     if ($actual_contexts !== $expected_contexts) {
         debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
         debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
     }
     $this->assertIdentical($actual_tags, $expected_tags);
     if ($actual_tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
     }
     // Assert page cache item + expected cache tags.
     $cid_parts = array($url->setAbsolute()->toString(), 'html');
     $cid = implode(':', $cid_parts);
     $cache_entry = \Drupal::cache('render')->get($cid);
     sort($cache_entry->tags);
     $this->assertEqual($cache_entry->tags, $expected_tags);
     if ($cache_entry->tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
     }
 }
Example #9
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, $pid = NULL)
 {
     $form = parent::buildForm($form, $form_state, $pid);
     $form['#title'] = $this->path['alias'];
     $form['pid'] = array('#type' => 'hidden', '#value' => $this->path['pid']);
     $url = new Url('path.delete', array('pid' => $this->path['pid']));
     if ($this->getRequest()->query->has('destination')) {
         $url->setOption('query', $this->getDestinationArray());
     }
     $form['actions']['delete'] = array('#type' => 'link', '#title' => $this->t('Delete'), '#url' => $url, '#attributes' => array('class' => array('button', 'button--danger')));
     return $form;
 }
Example #10
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, array &$form_state)
 {
     $brand = $this->entity;
     $status = $brand->save();
     if ($status) {
         // Setting the success message.
         drupal_set_message($this->t('Saved the brand: @name.', array('@name' => $brand->name)));
     } else {
         drupal_set_message($this->t('The @name brand was not saved.', array('@name' => $brand->name)));
     }
     $url = new Url('brandConfig.list');
     $form_state['redirect'] = $url->toString();
 }
Example #11
0
 /**
  * {@inheritdoc}
  */
 public function save(array $form, array &$form_state)
 {
     $sirenMapper = $this->entity;
     $status = $sirenMapper->save();
     if ($status) {
         // Setting the success message.
         drupal_set_message($this->t('Saved the siren mapper: @name.', array('@name' => $sirenMapper->name)));
     } else {
         drupal_set_message($this->t('The @name siren mapper was not saved.', array('@name' => $sirenMapper->name)));
     }
     $url = new Url('siren_mapper.list');
     $form_state['redirect'] = $url->toString();
 }
Example #12
0
 /**
  * {@inheritdoc}
  *
  * For anonymous users, the "active" class will be calculated on the server,
  * because most sites serve each anonymous user the same cached page anyway.
  * For authenticated users, the "active" class will be calculated on the
  * client (through JavaScript), only data- attributes are added to links to
  * prevent breaking the render cache. The JavaScript is added in
  * system_page_attachments().
  *
  * @see system_page_attachments()
  */
 public function generate($text, Url $url)
 {
     // Performance: avoid Url::toString() needing to retrieve the URL generator
     // service from the container.
     $url->setUrlGenerator($this->urlGenerator);
     // Start building a structured representation of our link to be altered later.
     $variables = array('text' => is_array($text) ? drupal_render($text) : $text, 'url' => $url, 'options' => $url->getOptions());
     // Merge in default options.
     $variables['options'] += array('attributes' => array(), 'query' => array(), 'language' => NULL, 'set_active_class' => FALSE, 'absolute' => FALSE);
     // Add a hreflang attribute if we know the language of this link's url and
     // hreflang has not already been set.
     if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {
         $variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();
     }
     // Set the "active" class if the 'set_active_class' option is not empty.
     if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {
         // Add a "data-drupal-link-query" attribute to let the
         // drupal.active-link library know the query in a standardized manner.
         if (!empty($variables['options']['query'])) {
             $query = $variables['options']['query'];
             ksort($query);
             $variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);
         }
         // Add a "data-drupal-link-system-path" attribute to let the
         // drupal.active-link library know the path in a standardized manner.
         if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {
             // @todo System path is deprecated - use the route name and parameters.
             $system_path = $url->getInternalPath();
             // Special case for the front page.
             $variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;
         }
     }
     // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
     // only when a quick strpos() gives suspicion tags are present.
     if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
         $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
     }
     // Allow other modules to modify the structure of the link.
     $this->moduleHandler->alter('link', $variables);
     // Move attributes out of options. generateFromRoute(() doesn't need them.
     $attributes = new Attribute($variables['options']['attributes']);
     unset($variables['options']['attributes']);
     $url->setOptions($variables['options']);
     // The result of the url generator is a plain-text URL. Because we are using
     // it here in an HTML argument context, we need to encode it properly.
     $url = String::checkPlain($url->toString());
     // Make sure the link text is sanitized.
     $safe_text = SafeMarkup::escape($variables['text']);
     return SafeMarkup::set('<a href="' . $url . '"' . $attributes . '>' . $safe_text . '</a>');
 }
Example #13
0
 public function attachTo(array &$build, $display_id, Url $feed_url, $title)
 {
     $url_options = array();
     $input = $this->view->getExposedInput();
     if ($input) {
         $url_options['query'] = $input;
     }
     $url_options['absolute'] = TRUE;
     $url = $feed_url->setOptions($url_options)->toString();
     // Add the RSS icon to the view.
     $this->view->feedIcons[] = ['#theme' => 'feed_icon', '#url' => $url, '#title' => $title];
     // Attach a link to the RSS feed, which is an alternate representation.
     $build['#attached']['html_head_link'][][] = array('rel' => 'alternate', 'type' => 'application/rss+xml', 'title' => $title, 'href' => $url);
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public function getElement(array &$form, FormStateInterface $form_state)
 {
     // Construct the group elements.
     $group = $this->getGroup($form, $form_state);
     $plugin_id = $this->getPluginId();
     if (!isset($group->{$plugin_id})) {
         // Set properties from the plugin definition.
         foreach ($this->getElementProperties() as $name => $value) {
             $group->{$plugin_id}->setProperty($name, $value);
         }
         // Set default value from the stored form state value or theme setting.
         $default_value = $form_state->getValue($plugin_id, $this->theme->getSetting($plugin_id));
         $group->{$plugin_id}->setProperty('default_value', $default_value);
         // Append additional "see" link references to the description.
         $description = (string) $group->{$plugin_id}->getProperty('description') ?: '';
         /** @var \Drupal\Core\Render\Renderer $renderer */
         $renderer = \Drupal::service('renderer');
         $links = [];
         foreach ($this->pluginDefinition['see'] as $url => $title) {
             $link = ['#type' => 'link', '#url' => Url::fromUri($url), '#title' => $title, '#attributes' => ['target' => '_blank']];
             $links[] = (string) $renderer->render($link);
         }
         if (!empty($links)) {
             $description .= '<br>';
             $description .= t('See also:');
             $description .= ' ' . implode(', ', $links);
             $group->{$plugin_id}->setProperty('description', $description);
         }
     }
     return $group->{$plugin_id};
 }
Example #15
0
 /**
  * Tests menu link for route with access check.
  *
  * @see \Drupal\menu_test\Access\AccessCheck::access()
  */
 public function testMenuBlockLinksAccessCheck()
 {
     $this->drupalPlaceBlock('system_menu_block:account');
     // Test that there's link rendered on the route.
     $this->drupalGet('menu_test_access_check_session');
     $this->assertLink('Test custom route access check');
     // Page still accessible but thre should not be menu link.
     $this->drupalGet('menu_test_access_check_session');
     $this->assertResponse(200);
     $this->assertNoLink('Test custom route access check');
     // Test that page is no more accessible.
     $this->drupalGet('menu_test_access_check_session');
     $this->assertResponse(403);
     // Check for access to a restricted local task from a default local task.
     $this->drupalGet('foo/asdf');
     $this->assertResponse(200);
     $this->assertLinkByHref('foo/asdf');
     $this->assertLinkByHref('foo/asdf/b');
     $this->assertNoLinkByHref('foo/asdf/c');
     // Attempt to access a restricted local task.
     $this->drupalGet('foo/asdf/c');
     $this->assertResponse(403);
     $elements = $this->xpath('//ul[@class=:class]/li/a[@href=:href]', array(':class' => 'tabs primary', ':href' => Url::fromRoute('menu_test.router_test1', ['bar' => 'asdf'])->toString()));
     $this->assertTrue(empty($elements), 'No tab linking to foo/asdf found');
     $this->assertNoLinkByHref('foo/asdf/b');
     $this->assertNoLinkByHref('foo/asdf/c');
 }
 /**
  * Assert that a trail exists in the internal browser.
  *
  * @param array $trail
  *   An associative array whose keys are expected breadcrumb link paths and
  *   whose values are expected breadcrumb link texts (not sanitized).
  */
 protected function assertBreadcrumbParts($trail)
 {
     // Compare paths with actual breadcrumb.
     $parts = $this->getBreadcrumbParts();
     $pass = TRUE;
     // There may be more than one breadcrumb on the page. If $trail is empty
     // this test would go into an infinite loop, so we need to check that too.
     while ($trail && !empty($parts)) {
         foreach ($trail as $path => $title) {
             // If the path is empty, generate the path from the <front> route.  If
             // the path does not start with a leading slash, then run it through
             // Url::fromUri('base:')->toString() to get the correct base
             // prepended.
             if ($path == '') {
                 $url = Url::fromRoute('<front>')->toString();
             } elseif ($path[0] != '/') {
                 $url = Url::fromUri('base:' . $path)->toString();
             } else {
                 $url = $path;
             }
             $part = array_shift($parts);
             $pass = $pass && $part['href'] === $url && $part['text'] === SafeMarkup::checkPlain($title);
         }
     }
     // No parts must be left, or an expected "Home" will always pass.
     $pass = $pass && empty($parts);
     $this->assertTrue($pass, format_string('Breadcrumb %parts found on @path.', array('%parts' => implode(' » ', $trail), '@path' => $this->getUrl())));
 }
Example #17
0
 /**
  * {@inheritdoc}
  */
 public function buildRow(EntityInterface $entity)
 {
     /* @var $entity \Drupal\eck\Entity\EckEntity */
     $row['id'] = $entity->id();
     $row['title'] = \Drupal::l($this->getLabel($entity), Url::fromRoute('entity.' . $this->entityTypeId . '.canonical', array($this->entityTypeId => $entity->id())));
     return array_merge($row, parent::buildRow($entity));
 }
 /**
  * Displays links to all products that have not been categorized.
  *
  * @return
  *   Renderable form array.
  */
 public function orphans()
 {
     $build = array();
     if ($this->config('taxonomy.settings')->get('maintain_index_table')) {
         $vid = $this->config('uc_catalog.settings')->get('vocabulary');
         $product_types = uc_product_types();
         $field = FieldStorageConfig::loadByName('node', 'taxonomy_catalog');
         //@todo - figure this out
         // $field is a config object, not an array, so this doesn't work.
         //$types = array_intersect($product_types, $field['bundles']['node']);
         $types = $product_types;
         //temporary to get this to work at all
         $result = db_query('SELECT DISTINCT n.nid, n.title FROM {node_field_data} n LEFT JOIN (SELECT ti.nid, td.vid FROM {taxonomy_index} ti LEFT JOIN {taxonomy_term_data} td ON ti.tid = td.tid WHERE td.vid = :vid) txnome ON n.nid = txnome.nid WHERE n.type IN (:types[]) AND txnome.vid IS NULL', [':vid' => $vid, ':types[]' => $types]);
         $rows = array();
         while ($node = $result->fetchObject()) {
             $rows[] = $this->l($node->title, Url::fromRoute('entity.node.edit_form', ['node' => $node->nid], ['query' => ['destination' => 'admin/store/products/orphans']]));
         }
         if (count($rows) > 0) {
             $build['orphans'] = array('#theme' => 'item_list', '#items' => $rows);
         } else {
             $build['orphans'] = array('#markup' => $this->t('All products are currently listed in the catalog.'), '#prefix' => '<p>', '#suffix' => '</p>');
         }
     } else {
         $build['orphans'] = array('#markup' => $this->t('The node terms index is not being maintained, so Ubercart can not determine which products are not entered into the catalog.'), '#prefix' => '<p>', '#suffix' => '</p>');
     }
     return $build;
 }
/**
 * Add items to the toolbar menu.
 *
 * The toolbar is a container for administrative and site-global interactive
 * components.
 *
 * The toolbar provides a common styling for items denoted by the
 * .toolbar-tab class.
 *
 * The toolbar provides a construct called a 'tray'. The tray is a container
 * for content. The tray may be associated with a toggle in the administration
 * bar. The toggle shows or hides the tray and is optimized for small and
 * large screens. To create this association, hook_toolbar() returns one or
 * more render elements of type 'toolbar_item', containing the toggle and tray
 * elements in its 'tab' and 'tray' properties.
 *
 * The following properties are available:
 *   - 'tab': A renderable array.
 *   - 'tray': Optional. A renderable array.
 *   - '#weight': Optional. Integer weight used for sorting toolbar items in
 *     administration bar area.
 *
 * This hook is invoked in toolbar_pre_render().
 *
 * @return
 *   An array of toolbar items, keyed by unique identifiers such as 'home' or
 *   'administration', or the short name of the module implementing the hook.
 *   The corresponding value is a render element of type 'toolbar_item'.
 *
 * @see toolbar_pre_render()
 * @ingroup toolbar_tabs
 */
function hook_toolbar()
{
    $items = array();
    // Add a search field to the toolbar. The search field employs no toolbar
    // module theming functions.
    $items['global_search'] = array('#type' => 'toolbar_item', 'tab' => array('#type' => 'search', '#attributes' => array('placeholder' => t('Search the site'), 'class' => array('search-global'))), '#weight' => 200, '#attached' => array('css' => array(drupal_get_path('module', 'search') . '/css/search.base.css')));
    // The 'Home' tab is a simple link, which is wrapped in markup associated
    // with a visual tab styling.
    $items['home'] = array('#type' => 'toolbar_item', 'tab' => array('#type' => 'link', '#title' => t('Home'), '#url' => Url::fromRoute('<front>'), '#options' => array('attributes' => array('title' => t('Home page'), 'class' => array('toolbar-icon', 'toolbar-icon-home')))), '#weight' => -20);
    // A tray may be associated with a tab.
    //
    // When the tab is activated, the tray will become visible, either in a
    // horizontal or vertical orientation on the screen.
    //
    // The tray should contain a renderable array. An optional #heading property
    // can be passed. This text is written to a heading tag in the tray as a
    // landmark for accessibility.
    $items['commerce'] = array('#type' => 'toolbar_item', 'tab' => array('#type' => 'link', '#title' => t('Shopping cart'), '#url' => Url::fromRoute('cart'), '#options' => array('html' => FALSE, 'attributes' => array('title' => t('Shopping cart')))), 'tray' => array('#heading' => t('Shopping cart actions'), 'shopping_cart' => array('#theme' => 'item_list', '#items' => array())), '#weight' => 150);
    // The tray can be used to render arbritrary content.
    //
    // A renderable array passed to the 'tray' property will be rendered outside
    // the administration bar but within the containing toolbar element.
    //
    // If the default behavior and styling of a toolbar tray is not desired, one
    // can render content to the toolbar element and apply custom theming and
    // behaviors.
    $items['user_messages'] = array('#type' => 'toolbar_item', 'tab' => array('#type' => 'link', '#theme' => 'user_message_toolbar_tab', '#theme_wrappers' => array(), '#title' => t('Messages'), '#url' => Url::fromRoute('user.message'), '#options' => array('attributes' => array('title' => t('Messages')))), 'tray' => array('#heading' => t('User messages'), 'messages' => array()), '#weight' => 125);
    return $items;
}
Example #20
0
 /**
  * {@inheritdoc}
  */
 public function getCancelUrl()
 {
     $entity_layout = $this->getEntityLayoutFromRouteMatch();
     $target_entity_type = $entity_layout->getTargetEntityType();
     $bundle_entity_type = $this->entityLayoutService->getTargetBundleEntityType($entity_layout);
     return Url::fromRoute("entity_layout.{$target_entity_type}.layout", [$bundle_entity_type => $this->entityLayout->getTargetBundle()]);
 }
 /**
  * Checks if a node's type requires a redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function purlCheckNodeContext(GetResponseEvent $event, $eventName, EventDispatcherInterface $dispatcher_interface)
 {
     $route_options = $this->routeMatch->getRouteObject()->getOptions();
     $isAdminRoute = array_key_exists('_admin_route', $route_options) && $route_options['_admin_route'];
     if (!$isAdminRoute && ($matched = $this->matchedModifiers->getMatched() && ($entity = $this->routeMatch->getParameter('node')))) {
         $node_type = $this->entityStorage->load($entity->bundle());
         $purl_settings = $node_type->getThirdPartySettings('purl');
         if (!isset($purl_settings['keep_context']) || !$purl_settings['keep_context']) {
             $url = \Drupal\Core\Url::fromRoute($this->routeMatch->getRouteName(), $this->routeMatch->getRawParameters()->all(), ['host' => Settings::get('purl_base_domain'), 'absolute' => TRUE]);
             try {
                 $redirect_response = new TrustedRedirectResponse($url->toString());
                 $redirect_response->getCacheableMetadata()->setCacheMaxAge(0);
                 $modifiers = $event->getRequest()->attributes->get('purl.matched_modifiers', []);
                 $new_event = new ExitedContextEvent($event->getRequest(), $redirect_response, $this->routeMatch, $modifiers);
                 $dispatcher_interface->dispatch(PurlEvents::EXITED_CONTEXT, $new_event);
                 $event->setResponse($new_event->getResponse());
                 return;
             } catch (RedirectLoopException $e) {
                 \Drupal::logger('redirect')->warning($e->getMessage());
                 $response = new Response();
                 $response->setStatusCode(503);
                 $response->setContent('Service unavailable');
                 $event->setResponse($response);
                 return;
             }
         }
     }
 }
 protected function setUp()
 {
     parent::setUp();
     $this->updateUrl = Url::fromRoute('system.db_update');
     $this->updateUser = $this->drupalCreateUser(array('administer software updates', 'access site in maintenance mode'));
     \Drupal::service('entity.definition_update_manager')->applyUpdates();
 }
 /**
  * {@inheritdoc}
  */
 public function getDefaultOperations(EntityInterface $entity)
 {
     /** @var \Drupal\commerce_tax\Entity\TaxRateInterface $entity */
     $operations = parent::getDefaultOperations($entity);
     $operations['rate_amounts'] = ['title' => $this->t('View rate amounts'), 'url' => Url::fromRoute('entity.commerce_tax_rate_amount.collection', ['commerce_tax_rate' => $entity->id()])];
     return $operations;
 }
 /**
  * Assert that an outbound path is altered to an expected value.
  *
  * @param $original
  *   A string with the original path that is run through generateFrommPath().
  * @param $final
  *   A string with the expected result after generateFrommPath().
  * @return
  *   TRUE if $original was correctly altered to $final, FALSE otherwise.
  */
 protected function assertUrlOutboundAlter($original, $final)
 {
     // Test outbound altering.
     $result = $this->container->get('url_generator')->generateFromPath($original);
     $final = Url::fromUri('internal:/' . $final)->toString();
     $this->assertIdentical($result, $final, format_string('Altered outbound URL %original, expected %final, and got %result.', array('%original' => $original, '%final' => $final, '%result' => $result)));
 }
Example #25
0
 /**
  * Tests rendering form elements without passing through
  * \Drupal::formBuilder()->doBuildForm().
  */
 function testDrupalRenderFormElements()
 {
     // Define a series of form elements.
     $element = array('#type' => 'button', '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
     $element = array('#type' => 'textfield', '#title' => $this->randomMachineName(), '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
     $element = array('#type' => 'password', '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
     $element = array('#type' => 'textarea', '#title' => $this->randomMachineName(), '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//textarea');
     $element = array('#type' => 'radio', '#title' => $this->randomMachineName(), '#value' => FALSE);
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
     $element = array('#type' => 'checkbox', '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
     $element = array('#type' => 'select', '#title' => $this->randomMachineName(), '#options' => array(0 => $this->randomMachineName(), 1 => $this->randomMachineName()));
     $this->assertRenderedElement($element, '//select');
     $element = array('#type' => 'file', '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
     $element = array('#type' => 'item', '#title' => $this->randomMachineName(), '#markup' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(':class' => 'form-type-item', ':markup' => $element['#markup'], ':label' => $element['#title']));
     $element = array('#type' => 'hidden', '#title' => $this->randomMachineName(), '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
     $element = array('#type' => 'link', '#title' => $this->randomMachineName(), '#url' => Url::fromRoute('common_test.destination'), '#options' => array('absolute' => TRUE));
     $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(':href' => \Drupal::urlGenerator()->generateFromPath('common-test/destination', ['absolute' => TRUE]), ':title' => $element['#title']));
     $element = array('#type' => 'details', '#open' => TRUE, '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//details/summary[contains(., :title)]', array(':title' => $element['#title']));
     $element = array('#type' => 'details', '#open' => TRUE, '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//details');
     $element['item'] = array('#type' => 'item', '#title' => $this->randomMachineName(), '#markup' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//details/div/div[contains(@class, :class) and contains(., :markup)]', array(':class' => 'form-type-item', ':markup' => $element['item']['#markup']));
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $fblikebutton_node_options = node_type_get_names();
     $config = $this->config('fblikebutton.settings');
     $form['fblikebutton_dynamic_visibility'] = array('#type' => 'details', '#title' => $this->t('Visibility settings'), '#open' => TRUE);
     $form['fblikebutton_dynamic_visibility']['fblikebutton_node_types'] = array('#type' => 'checkboxes', '#title' => $this->t('Display the Like button on these content types:'), '#options' => $fblikebutton_node_options, '#default_value' => $config->get('node_types'), '#description' => $this->t('Each of these content types will have the "like" button automatically added to them.'));
     /** 
      * @TODO: Uncomment this when the module is also able to add the button to 
      * the links area
      * 
     $form['fblikebutton_dynamic_visibility']['fblikebutton_full_node_display'] = array(
       '#type' => 'radios',
       '#title' => $this->t('Where do you want to show the Like button (full node view)?'),
       '#options' => array(
         $this->t('Content area'),
         $this->t('Links area')
       ),
       '#default_value' => $config->get('full_node_display'),
       '#description' => $this->t('If <em>Content area</em> is selected, the button will appear in the same area as the node content. When you select <em>Links area</em> the Like button will be visible in the links area, usually at the bottom of the node (When you select this last option you may want to adjust the Appearance settings). You can also configure Static Like Button Blocks in'. \Drupal::l($this->t('block page'), Url::fromRoute('block.admin_display')) . '.'),
     );
     */
     $form['fblikebutton_dynamic_visibility']['fblikebutton_teaser_display'] = array('#type' => 'radios', '#title' => $this->t('Where do you want to show the Like button on teasers?'), '#options' => array($this->t('Don\'t show on teasers'), $this->t('Content area')), '#default_value' => $config->get('teaser_display'), '#description' => $this->t('If you want to show the like button on teasers you can select the display area.'));
     $form['fblikebutton_dynamic_appearance'] = array('#type' => 'details', '#title' => $this->t('Appearance settings'), '#open' => TRUE);
     $form['fblikebutton_dynamic_appearance']['fblikebutton_layout'] = array('#type' => 'select', '#title' => $this->t('Layout style'), '#options' => array('standard' => $this->t('Standard'), 'box_count' => $this->t('Box Count'), 'button_count' => $this->t('Button Count'), 'button' => $this->t('Button')), '#default_value' => $config->get('layout'), '#description' => $this->t('Determines the size and amount of social context next to the button.'));
     // The actial values passed in from the options will be converted to a boolean
     // in the validation function, so it doesn't really matter what we use.
     $form['fblikebutton_dynamic_appearance']['fblikebutton_show_faces'] = array('#type' => 'select', '#title' => $this->t('Show faces in the box?'), '#options' => array(t('Do not show faces'), $this->t('Show faces')), '#default_value' => $config->get('show_faces', TRUE), '#description' => $this->t('Show profile pictures below the button. Only works if <em>Layout style</em> (found above) is set to <em>Standard</em> (otherwise, value is ignored).'));
     $form['fblikebutton_dynamic_appearance']['fblikebutton_action'] = array('#type' => 'select', '#title' => $this->t('Verb to display'), '#options' => array('like' => $this->t('Like'), 'recommend' => $this->t('Recommend')), '#default_value' => $config->get('action'), '#description' => $this->t('The verbiage to display inside the button itself.'));
     $form['fblikebutton_dynamic_appearance']['fblikebutton_font'] = array('#type' => 'select', '#title' => $this->t('Font'), '#options' => array('arial' => 'Arial', 'lucida+grande' => 'Lucida Grande', 'segoe+ui' => 'Segoe UI', 'tahoma' => 'Tahoma', 'trebuchet+ms' => 'Trebuchet MS', 'verdana' => 'Verdana'), '#default_value' => $config->get('font', 'arial'), '#description' => $this->t('The font with which to display the text of the button.'));
     $form['fblikebutton_dynamic_appearance']['fblikebutton_color_scheme'] = array('#type' => 'select', '#title' => $this->t('Color scheme'), '#options' => array('light' => $this->t('Light'), 'dark' => $this->t('Dark')), '#default_value' => $config->get('color_scheme'), '#description' => $this->t('The color scheme of the box environtment.'));
     $form['fblikebutton_dynamic_appearance']['fblikebutton_weight'] = array('#type' => 'number', '#title' => $this->t('Weight'), '#default_value' => $config->get('weight'), '#description' => $this->t('The weight determines where, at the content block, the like button will appear. The larger the weight, the lower it will appear on the node. For example, if you want the button to appear more toward the top of the node, choose <em>-40</em> as opposed to <em>-39, -38, 0, 1,</em> or <em>50,</em> etc. To position the Like button in its own block, go to the ' . \Drupal::l($this->t('block page'), Url::fromRoute('block.admin_display')) . '.'));
     $form['fblikebutton_dynamic_appearance']['fblikebutton_language'] = array('#type' => 'textfield', '#title' => $this->t('Language'), '#default_value' => $config->get('language'), '#description' => $this->t('Specific language to use. Default is English. Examples:<br />French (France): <em>fr_FR</em><br />French (Canada): <em>fr_CA</em><br />More information can be found at http://developers.facebook.com/docs/internationalization/ and a full XML list can be found at http://www.facebook.com/translations/FacebookLocales.xml'));
     return parent::buildForm($form, $form_state);
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $block = array('#theme' => 'fblikebutton', '#layout' => $this->configuration['layout'], '#show_faces' => $this->configuration['show_faces'], '#action' => $this->configuration['action'], '#font' => $this->configuration['font'], '#color_scheme' => $this->configuration['color_scheme'], '#width' => $this->configuration['iframe_width'], '#height' => $this->configuration['iframe_height'], '#other_css' => $this->configuration['iframe_css'], '#language' => $this->configuration['language']);
     // If it's not for the current page
     if ($this->configuration['block_url'] != '<current>') {
         $block['#url'] = $this->configuration['block_url'];
     } else {
         // Avoid this block to be cached
         $block['#cache'] = array('max-age' => 0);
         /**
          * Drupal uses the /node path to refers to the frontpage. That's why facebook
          * could point to www.example.com/node instead of wwww.example.com.
          * 
          * To avoid this, we check if the current path is the frontpage
          */
         // Check if the path is pointing home
         if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
             global $base_url;
             $block['#url'] = $base_url;
         } else {
             $block['#url'] = Url::fromRoute('<current>', array(), array('absolute' => true))->toString();
         }
     }
     return $block;
 }
Example #28
0
 /**
  * {@inheritdoc}
  */
 public function view(OrderInterface $order, $view_mode)
 {
     if ($view_mode == 'customer' && $order->access('invoice')) {
         $build = array('#type' => 'link', '#title' => $this->t('Click to open a window with a printable invoice.'), '#url' => Url::fromRoute('uc_order.user_invoice_print', ['user' => $order->getOwnerId(), 'uc_order' => $order->id()], array('attributes' => array('onclick' => "window.open(this.href, '" . $this->t('Invoice') . "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=480,left=50,top=50'); return false;"))));
         return $build;
     }
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL)
 {
     $config = $this->config('easychart.settings');
     $load_defaults = FALSE;
     // Get defaults.
     foreach ($this->getDefaults() as $default) {
         // Verify default options.
         $default_value = $config->get($default);
         if (empty($default_value)) {
             // Set flag to true.
             $load_defaults = TRUE;
             $form['#attached']['drupalSettings']['easychart'][$default] = TRUE;
         }
     }
     if ($load_defaults) {
         $form['#attached']['library'][] = 'easychart/easychart.defaults';
         $form['#attached']['library'][] = 'easychart/lib.easycharts.full';
     }
     $options = $config->get('options');
     $form['options'] = ['#type' => 'textarea', '#title' => $this->t('Available options'), '#description' => $this->t('These Highcharts options will be configurable in the Easychart interface when creating/editing a chart. See <a href="@url" target="_blank">http://api.highcharts.com/highcharts</a> for all available options.', array('@url' => Url::fromUri('http://api.highcharts.com/highcharts')->toUriString())), '#default_value' => $options, '#attributes' => array('class' => array('easychart-options')), '#rows' => 15];
     $form['templates'] = ['#type' => 'textarea', '#title' => t('Available templates'), '#default_value' => $config->get('templates'), '#description' => t("These templates will be selectable in the Easychart interface when creating/editing a chart."), '#attributes' => array('class' => array('easychart-templates')), '#rows' => 15];
     $form['presets'] = ['#type' => 'textarea', '#title' => t('Presets'), '#default_value' => $config->get('presets'), '#description' => $this->t('Presets for every Easychart chart. If these preset are also mentioned in the available options, they will be shown, but not editable.'), '#attributes' => array('class' => array('easychart-presets')), '#rows' => 10];
     $interval = array(3600, 10800, 21600, 32400, 43200, 86400, 172800);
     $form['url_update_frequency'] = ['#type' => 'select', '#title' => t('Update frequency'), '#options' => array(0 => t('Never')) + array_map([\Drupal::service('date.formatter'), 'formatInterval'], array_combine($interval, $interval)), '#default_value' => $config->get('url_update_frequency'), '#description' => $this->t('When to update the data for charts using a CSV URL.'), '#rows' => 10];
     $form['actions']['reset'] = ['#type' => 'submit', '#value' => t('Reset to defaults'), '#submit' => array('::resetForm'), '#limit_validation_errors' => array(), '#weight' => 100];
     return parent::buildForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  *
  * TODO: Use $langcode.
  */
 public function viewElements(FieldItemListInterface $items, $langcode)
 {
     $element = array();
     $settings = $this->getFieldSettings();
     $count = 0;
     // TODO: Is there a better way to get an accurate count of the
     // items from the FieldItemList that doesn't count blank items?
     // Possibly \Countable->count()?
     $storage = \Drupal::entityTypeManager()->getStorage('field_collection_item');
     foreach ($items as $delta => $item) {
         if ($item->value !== NULL) {
             $count++;
             $field_collection_item = $storage->loadRevision($item->revision_id);
             if ($field_collection_item->isDefaultRevision()) {
                 $links = \Drupal::l($this->fieldDefinition->getName() . ' ' . $delta, Url::FromRoute('entity.field_collection_item.canonical', array('field_collection_item' => $item->value)));
                 $links .= ' ' . $this->getEditLinks($item);
             } else {
                 $links = \Drupal::l($this->fieldDefinition->getName() . ' ' . $delta, Url::FromRoute('field_collection_item.revision_show', ['field_collection_item' => $item->value, 'field_collection_item_revision' => $item->revision_id]));
             }
             $element[$delta] = array('#markup' => $links);
         }
     }
     $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
     if ($cardinality == -1 || $count < $cardinality) {
         $element['#suffix'] = '<ul class="action-links action-links-field-collection-add"><li>';
         $element['#suffix'] .= $this->getAddLink($items->getEntity());
         $element['#suffix'] .= '</li></ul>';
     }
     return $element;
 }