fromTextAndUrl example

'administer blocks',
      'access site reports',
    ]);
    $this->drupalLogin($this->searchUser);

    // Add a single piece of content and index it.     $node = $this->drupalCreateNode();
    $this->searchNode = $node;
    // Link the node to itself to test that it's only indexed once. The content     // also needs the word "pizza" so we can use it as the search keyword.     $body_key = 'body[0][value]';
    $edit[$body_key] = Link::fromTextAndUrl($node->label()$node->toUrl())->toString() . ' pizza sandwich';
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->submitForm($edit, 'Save');

    $this->container->get('plugin.manager.search')->createInstance('node_search')->updateIndex();

    // Enable the search block.     $this->drupalPlaceBlock('search_form_block');
    $this->drupalPlaceBlock('local_tasks_block', ['id' => 'local_tasks']);
    $this->drupalPlaceBlock('page_title_block');
  }

  
$field_name = $comment->getFieldName();
    $uri = $entity->toUrl();
    $logger = $this->logger('comment');

    if ($this->currentUser->hasPermission('post comments') && ($this->currentUser->hasPermission('administer comments') || $entity->{$field_name}->status == CommentItemInterface::OPEN)) {
      $comment->save();
      $form_state->setValue('cid', $comment->id());

      // Add a log entry.       $logger->notice('Comment posted: %subject.', [
        '%subject' => $comment->getSubject(),
        'link' => Link::fromTextAndUrl(t('View')$comment->toUrl()->setOption('fragment', 'comment-' . $comment->id()))->toString(),
      ]);

      // Explain the approval queue if necessary.       if (!$comment->isPublished()) {
        if (!$this->currentUser->hasPermission('administer comments')) {
          $this->messenger()->addStatus($this->t('Your comment has been queued for review by site administrators and will be published after approval.'));
        }
      }
      else {
        $this->messenger()->addStatus($this->t('Your comment has been posted.'));
      }
      
$text = $this->t('Broken field');
    }

    if (!empty($class)) {
      $text = new FormattableMarkup('<span>@text</span>', ['@text' => $text]);
    }

    if (empty($title)) {
      $title = $text;
    }

    return Link::fromTextAndUrl($text, Url::fromRoute('views_ui.form_display', [
      'js' => 'nojs',
      'view' => $this->view->storage->id(),
      'display_id' => $this->display['id'],
      'type' => $section,
    ][
      'attributes' => [
        'class' => ['views-ajax-link', $class],
        'title' => $title,
        'id' => Html::getUniqueId('views-' . $this->display['id'] . '-' . $section),
      ],
    ]))->toString();
  }

              [
                'data' => [
                  '#markup' => $executable->getTitle(),
                  '#allowed_tags' => Xss::getHtmlTagList(),
                ],
              ],
            ];
            if (isset($path)) {
              // @todo Views should expect and store a leading /. See:               // https://www.drupal.org/node/2423913               $path = Link::fromTextAndUrl($path->toString()$path)->toString();
            }
            else {
              $path = t('This display has no path.');
            }
            $rows['query'][] = [
              [
                'data' => [
                  '#prefix' => '<strong>',
                  '#markup' => t('Path'),
                  '#suffix' => '</strong>',
                ],
              ],
$view->displayHandlers->get('default')->overrideOption('fields', [
      'name' => [
        'id' => 'name',
        'table' => 'views_test_data',
        'field' => 'name',
        'relationship' => 'none',
      ],
    ]);

    $this->executeView($view);

    $this->assertEquals(Link::fromTextAndUrl('John', Url::fromUri('base:John'))->toString()$view->field['name']->advancedRender($view->result[0]));
  }

}
$this->assertSession()->pageTextContains('Last viewed');

    $tags = Cache::mergeTags($node->getCacheTags()$block->getCacheTags());
    $tags = Cache::mergeTags($tags$this->blockingUser->getCacheTags());
    $tags = Cache::mergeTags($tags['block_view', 'config:block_list', 'node_list', 'rendered', 'user_view']);
    $this->assertCacheTags($tags);
    $contexts = Cache::mergeContexts($node->getCacheContexts()$block->getCacheContexts());
    $contexts = Cache::mergeContexts($contexts['url.query_args:_wrapper_format', 'url.site']);
    $this->assertCacheContexts($contexts);

    // Check if the node link is displayed.     $this->assertSession()->responseContains(Link::fromTextAndUrl($node->label()$node->toUrl('canonical'))->toString());
  }

}
      // children with a title.       $has_title = !empty($title);
      // Only show links for elements with an ID.       $has_id = !empty($form_element['#id']);

      // Do not show links to elements with suppressed messages. Most often       // their parent element is used for inline errors.       if (!empty($form_element['#error_no_message'])) {
        unset($errors[$name]);
      }
      elseif ($is_visible_element && $has_title && $has_id) {
        $error_links[] = Link::fromTextAndUrl($title, Url::fromRoute('<none>', []['fragment' => $form_element['#id'], 'external' => TRUE]))->toRenderable();
        unset($errors[$name]);
      }
    }

    // Set normal error messages for all remaining errors.     foreach ($errors as $error) {
      $this->messenger->addError($error);
    }

    if (!empty($error_links)) {
      $render_array = [
        [
parent::buildOptionsForm($form$form_state);
  }

  /** * {@inheritdoc} */
  public function render(ResultRow $values) {
    $value = $this->getValue($values);
    if (!empty($this->options['display_as_link'])) {
      // @todo Views should expect and store a leading /. See:       // https://www.drupal.org/node/2423913       return Link::fromTextAndUrl($this->sanitizeValue($value), CoreUrl::fromUserInput('/' . $value))->toString();
    }
    else {
      return $this->sanitizeValue($value, 'url');
    }
  }

}

          }
        }
      }
    }

    $header = [t('Field name')t('Used in')];
    $rows = [];
    foreach ($fields as $field_name => $views) {
      $rows[$field_name]['data'][0]['data']['#plain_text'] = $field_name;
      foreach ($views as $view) {
        $rows[$field_name]['data'][1][] = Link::fromTextAndUrl($viewnew Url('entity.view.edit_form', ['view' => $view]))->toString();
      }
      $item_list = [
        '#theme' => 'item_list',
        '#items' => $rows[$field_name]['data'][1],
        '#context' => ['list_style' => 'comma-list'],
      ];
      $rows[$field_name]['data'][1] = ['data' => $item_list];
    }

    // Sort rows by field name.     ksort($rows);
    
$entity_type_id = $field_storage->getTargetEntityTypeId();
    // Adding the entity type.     $row['data']['entity_type'] = $entity_type_id;

    $field_type = $this->fieldTypes[$field_storage->getType()];
    $row['data']['type'] = $this->t('@type (module: @module)', ['@type' => $field_type['label'], '@module' => $field_type['provider']]);

    $usage = [];
    foreach ($field_storage->getBundles() as $bundle) {
      if ($route_info = FieldUI::getOverviewRouteInfo($entity_type_id$bundle)) {
        $usage[] = Link::fromTextAndUrl($this->bundles[$entity_type_id][$bundle]['label']$route_info)->toRenderable();
      }
      else {
        $usage[] = $this->bundles[$entity_type_id][$bundle]['label'];
      }
    }
    $row['data']['usage']['data'] = [
      '#theme' => 'item_list',
      '#items' => $usage,
      '#context' => ['list_style' => 'comma-list'],
    ];
    $summary = $this->fieldTypeManager->getStorageSettingsSummary($field_storage);
    

  public function verifySort($sort = 'asc', $order = 'Date') {
    $this->drupalGet('admin/reports/dblog', ['query' => ['sort' => $sort, 'order' => $order]]);
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('Recent log messages');
  }

  /** * Tests link escaping in the operation row of a database log detail page. */
  private function verifyLinkEscaping() {
    $link = Link::fromTextAndUrl('View', Url::fromRoute('entity.node.canonical', ['node' => 1]))->toString();
    $message = 'Log entry added to do the verifyLinkEscaping test.';
    $this->generateLogEntries(1, [
      'message' => $message,
      'link' => $link,
    ]);

    $result = Database::getConnection()->select('watchdog', 'w')->fields('w', ['wid'])->orderBy('wid', 'DESC')->range(0, 1)->execute();
    $this->drupalGet('admin/reports/dblog/event/' . $result->fetchField());

    // Check if the link exists (unescaped).     $this->assertSession()->responseContains($link);
  }
$rows = [];

    $headers = [t('Book')t('Operations')];
    // Add any recognized books to the table list.     foreach ($this->bookManager->getAllBooks() as $book) {
      /** @var \Drupal\Core\Url $url */
      $url = $book['url'];
      if (isset($book['options'])) {
        $url->setOptions($book['options']);
      }
      $row = [
        Link::fromTextAndUrl($book['title']$url),
      ];
      $links = [];
      $links['edit'] = [
        'title' => t('Edit order and titles'),
        'url' => Url::fromRoute('book.admin_edit', ['node' => $book['nid']]),
      ];
      $row[] = [
        'data' => [
          '#type' => 'operations',
          '#links' => $links,
        ],
      ];

class TestHelpSection extends HelpSectionPluginBase implements SearchableHelpInterface {

  /** * {@inheritdoc} */
  public function listTopics() {
    return [
      Link::fromTextAndUrl('Foo', Url::fromUri('https://foo.com')),
      Link::fromTextAndUrl('Bar', Url::fromUri('https://bar.com')),
    ];
  }

  /** * {@inheritdoc} */
  public function listSearchableTopics() {
    return ['foo', 'bar'];
  }

  
/** * Tests the Update Manager module when a major update is available. */
  public function testMajorUpdateAvailable() {
    foreach ([0, 1] as $minor_version) {
      foreach ([0, 1] as $patch_version) {
        foreach (['-alpha1', '-beta1', ''] as $extra_version) {
          $this->setProjectInstalledVersion("8.$minor_version.$patch_version" . $extra_version);
          $this->refreshUpdateStatus([$this->updateProject => '9']);
          $this->standardTests();
          $this->assertUpdateTableTextNotContains('Security update required!');
          $this->assertUpdateTableElementContains(Link::fromTextAndUrl('9.0.0', Url::fromUri("http://example.com/{$this->updateProject}-9-0-0-release"))->toString());
          $this->assertUpdateTableElementContains(Link::fromTextAndUrl('Release notes', Url::fromUri("http://example.com/{$this->updateProject}-9-0-0-release"))->toString());
          $this->assertUpdateTableTextNotContains('Up to date');
          $this->assertUpdateTableTextContains('Not supported!');
          $this->assertUpdateTableTextContains('Recommended version:');
          $this->assertUpdateTableTextNotContains('Latest version:');
          $this->assertUpdateTableElementContains('error.svg');
        }
      }
    }
  }

  
        // of pages instead of a single page.         try {
          $params = $route['route_params'] ?? [];
          $url = Url::fromRoute($route['route_name']$params);
          // Skip this route if the current user cannot access it.           if (!$url->access()) {
            continue;
          }

          // Generate the link HTML directly, using toString(), to catch           // missing parameter exceptions now instead of at render time.           $topics[$id] = Link::fromTextAndUrl($title$url)->toString();
          // If the line above didn't generate an exception, we have a good           // link that the user can access.           $made_link = TRUE;
          break;
        }
        catch (\Exception $e) {
          // Exceptions are normally due to routes that need parameters. If           // there is an exception, just try the next route and see if we can           // find one that will work for us.         }
      }
      
Home | Imprint | This part of the site doesn't use cookies.