fromRoute example


function hook_menu_local_tasks_alter(&$data$route_name, \Drupal\Core\Cache\RefinableCacheableDependencyInterface &$cacheability) {

  // Add a tab linking to node/add to all pages.   $data['tabs'][0]['node.add_page'] = [
    '#theme' => 'menu_local_task',
    '#link' => [
      'title' => t('Example tab'),
      'url' => Url::fromRoute('node.add_page'),
      'localized_options' => [
        'attributes' => [
          'title' => t('Add content'),
        ],
      ],
    ],
  ];
  // The tab we're adding is dependent on a user's access to add content.   $cacheability->addCacheContexts(['user.permissions']);
}


  public function execute() {
    $results = [];
    if (!$this->isSearchExecutable()) {
      return $results;
    }
    return [
      [
        'link' => Url::fromRoute('test_page_test.test_page')->toString(),
        'type' => 'Dummy result type',
        'title' => 'Dummy title',
        'snippet' => new FormattableMarkup("Dummy search snippet to display. Keywords: @keywords\n\nConditions: @search_parameters", ['@keywords' => $this->keywords, '@search_parameters' => print_r($this->searchParameters, TRUE)]),
      ],
    ];
  }

  /** * {@inheritdoc} */
  public function buildResults() {
    

  public function testRouteAccess() {
    $client = $this->getHttpClient();
    $csrf_token_path = 'session/token';
    // Test using the current path.     $route_name = 'csrf_test.protected';
    $user = $this->drupalCreateUser();
    $this->drupalLogin($user);

    $csrf_token = $this->drupalGet($csrf_token_path);
    $url = Url::fromRoute($route_name)
      ->setAbsolute(TRUE)
      ->toString();
    $post_options = [
      'headers' => ['Accept' => 'text/plain'],
      'http_errors' => FALSE,
    ];

    // Test that access is allowed for anonymous user with no token in header.     $result = $client->post($url$post_options);
    $this->assertEquals(200, $result->getStatusCode());

    
      // testing Attribute object merging with the twig link() function.       '#attributes' => new Attribute(['class' => ['llama', 'kitten', 'panda']]),
    ];
  }

  /** * Renders a URL to a string. */
  public function urlToStringRender() {
    return [
      '#theme' => 'twig_theme_test_url_to_string',
      '#test_url' => Url::fromRoute('user.register'),
    ];
  }

  /** * Renders for testing file_url functions in a Twig template. */
  public function fileUrlRender() {
    return [
      '#theme' => 'twig_theme_test_file_url',
    ];
  }

  

  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form$form_state);
    $form['shortcuts'] = [
      '#tree' => TRUE,
      '#weight' => -20,
    ];

    $form['shortcuts']['links'] = [
      '#type' => 'table',
      '#header' => [$this->t('Name')$this->t('Weight')$this->t('Operations')],
      '#empty' => $this->t('No shortcuts available. <a href=":link">Add a shortcut</a>', [':link' => Url::fromRoute('shortcut.link_add', ['shortcut_set' => $this->entity->id()])->toString()]),
      '#attributes' => ['id' => 'shortcuts'],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'shortcut-weight',
        ],
      ],
    ];

    foreach ($this->entity->getShortcuts() as $shortcut) {
      
    $nids = array_slice($nids, 0, 100);

    $links = [];
    foreach ($nids as $nid) {
      $node = $this->entityTypeManager()->getStorage('node')->load($nid);
      $new = $this->commentManager->getCountNewComments($node);
      $page_number = $this->entityTypeManager()->getStorage('comment')
        ->getNewCommentPageNumber($node->{$field_name}->comment_count, $new$node$field_name);
      $query = $page_number ? ['page' => $page_number] : NULL;
      $links[$nid] = [
        'new_comment_count' => (int) $new,
        'first_new_comment_link' => Url::fromRoute('entity.node.canonical', ['node' => $node->id()]['query' => $query, 'fragment' => 'new'])->toString(),
      ];
    }

    return new JsonResponse($links);
  }

}
    \Drupal::service('module_installer')->install(['responsive_image']);
    $this->rebuildContainer();
    $this->drupalGet('admin/config/media/image-styles');
    $this->assertSession()->pageTextContains('Max 325x325');
    $this->assertSession()->pageTextContains('Max 650x650');
    $this->assertSession()->pageTextContains('Max 1300x1300');
    $this->assertSession()->pageTextContains('Max 2600x2600');

    // Verify certain routes' responses are cacheable by Dynamic Page Cache, to     // ensure these responses are very fast for authenticated users.     $this->drupalLogin($this->adminUser);
    $url = Url::fromRoute('contact.site_page');
    $this->drupalGet($url);
    // Verify that site-wide contact page cannot be cached by Dynamic Page     // Cache.     $this->assertSession()->responseHeaderEquals(DynamicPageCacheSubscriber::HEADER, 'UNCACHEABLE');

    $url = Url::fromRoute('<front>');
    $this->drupalGet($url);
    $this->drupalGet($url);
    // Verify that frontpage is cached by Dynamic Page Cache.     $this->assertSession()->responseHeaderEquals(DynamicPageCacheSubscriber::HEADER, 'HIT');

    
foreach ($definitions as $plugin_id => $definition) {
      $layout = $this->layoutManager->createInstance($plugin_id);
      $item = [
        '#type' => 'link',
        '#title' => [
          'icon' => $definition->getIcon(60, 80, 1, 3),
          'label' => [
            '#type' => 'container',
            '#children' => $definition->getLabel(),
          ],
        ],
        '#url' => Url::fromRoute(
          $layout instanceof PluginFormInterface ? 'layout_builder.configure_section' : 'layout_builder.add_section',
          [
            'section_storage_type' => $section_storage->getStorageType(),
            'section_storage' => $section_storage->getStorageId(),
            'delta' => $delta,
            'plugin_id' => $plugin_id,
          ]
        ),
      ];
      if ($this->isAjax()) {
        $item['#attributes']['class'][] = 'use-ajax';
        
    $en_edit_url = $entity->toUrl('edit-form');
    $this->drupalGet($en_edit_url);
    $field_xpath = '//input[@name="' . $this->fieldName . '[0][value]"]';
    $this->assertSession()->elementExists('xpath', $field_xpath);
    $clue_xpath = '//label[@for="edit-' . strtr($this->fieldName, '_', '-') . '-0-value"]/span[text()="(all languages)"]';
    $this->assertSession()->elementNotExists('xpath', $clue_xpath);
    $this->assertSession()->pageTextContains('Untranslatable-but-visible test field');

    // Add a translation and check that the untranslatable field widget is     // displayed on the translation and edit forms along with translatability     // clues.     $add_url = Url::fromRoute("entity.{$this->entityTypeId}.content_translation_add", [
      $entity->getEntityTypeId() => $entity->id(),
      'source' => 'en',
      'target' => 'it',
    ]);
    $this->drupalGet($add_url);
    $this->assertSession()->elementExists('xpath', $field_xpath);
    $this->assertSession()->elementExists('xpath', $clue_xpath);
    $this->assertSession()->pageTextContains('Untranslatable-but-visible test field');
    $this->submitForm([], 'Save');

    // Check that the widget is displayed along with its clue in the edit form
$form['update_notification_threshold'] = [
      '#type' => 'radios',
      '#title' => $this->t('Email notification threshold'),
      '#default_value' => $config->get('notification.threshold'),
      '#options' => [
        'all' => $this->t('All newer versions'),
        'security' => $this->t('Only security updates'),
      ],
      '#description' => $this->t(
        'You can choose to send email only if a security update is available, or to be notified about all newer versions. If there are updates available of Drupal core or any of your installed modules and themes, your site will always print a message on the <a href=":status_report">status report</a> page. If there is a security update, an error message will be printed on administration pages for users with <a href=":update_permissions">permission to view update notifications</a>.',
        [
          ':status_report' => Url::fromRoute('system.status')->toString(),
          ':update_permissions' => Url::fromRoute('user.admin_permissions', []['fragment' => 'module-update'])->toString(),
        ]
      ),
    ];

    return parent::buildForm($form$form_state);
  }

  /** * {@inheritdoc} */
  

  protected $logoutToken;

  /** * {@inheritdoc} */
  protected function initAuthentication() {
    $user_login_url = Url::fromRoute('user.login.http')
      ->setRouteParameter('_format', static::$format);

    $request_body = [
      'name' => $this->account->name->value,
      'pass' => $this->account->passRaw,
    ];

    $request_options[RequestOptions::BODY] = $this->serializer->encode($request_bodystatic::$format);
    $request_options[RequestOptions::HEADERS] = [
      'Content-Type' => static::$mimeType,
    ];
    

  public function getRedirectUrl() {
    return $this->getEntity()->toUrl('canonical');
  }

  /** * {@inheritdoc} */
  public function getLayoutBuilderUrl($rel = 'view') {
    $entity = $this->getEntity();
    $route_parameters[$entity->getEntityTypeId()] = $entity->id();
    return Url::fromRoute("layout_builder.{$this->getStorageType()}.{$this->getEntity()->getEntityTypeId()}.$rel", $route_parameters);
  }

  /** * {@inheritdoc} */
  public function getContextsDuringPreview() {
    $contexts = parent::getContextsDuringPreview();

    // @todo Remove this in https://www.drupal.org/node/3018782.     if (isset($contexts['entity'])) {
      $contexts['layout_builder.entity'] = $contexts['entity'];
      
$this->submitForm([
      'title[0][value]' => 'Some moderated content',
      'body[0][value]' => 'First version of the content.',
      'moderation_state[0][state]' => 'draft',
    ], 'Save');

    $node = $this->drupalGetNodeByTitle('Some moderated content');
    $edit_path = sprintf('node/%d/edit', $node->id());

    // After saving, we should be at the canonical URL and viewing the first     // revision.     $this->assertSession()->addressEquals(Url::fromRoute('entity.node.canonical', ['node' => $node->id()]));
    $this->assertSession()->pageTextContains('First version of the content.');

    // Create a new draft; after saving, we should still be on the canonical     // URL, but viewing the second revision.     $this->drupalGet($edit_path);
    $this->submitForm([
      'body[0][value]' => 'Second version of the content.',
      'moderation_state[0][state]' => 'draft',
    ], 'Save');
    $this->assertSession()->addressEquals(Url::fromRoute('entity.node.canonical', ['node' => $node->id()]));
    $this->assertSession()->pageTextContains('Second version of the content.');

    
    $this->drupalGet('form-test/confirm-form-array-path');
    $this->clickLink('ConfirmFormArrayPathTestForm::getCancelText().');
    // Verify that the form's complex cancel link was followed.     $this->assertSession()->addressEquals('form-test/confirm-form?destination=admin/config');
  }

  /** * Tests that the confirm form does not use external destinations. */
  public function testConfirmFormWithExternalDestination() {
    $this->drupalGet('form-test/confirm-form');
    $this->assertSession()->linkByHrefExists(Url::fromRoute('form_test.route8')->toString());
    $this->drupalGet('form-test/confirm-form', ['query' => ['destination' => 'node']]);
    $this->assertSession()->linkByHrefExists(Url::fromUri('internal:/node')->toString());
    $this->drupalGet('form-test/confirm-form', ['query' => ['destination' => 'http://example.com']]);
    $this->assertSession()->linkByHrefExists(Url::fromRoute('form_test.route8')->toString());
    $this->drupalGet('form-test/confirm-form', ['query' => ['destination' => '<front>']]);
    $this->assertSession()->linkByHrefExists(Url::fromRoute('<front>')->toString());
    // Other invalid destinations, should fall back to the form default.     $this->drupalGet('form-test/confirm-form', ['query' => ['destination' => '/http://example.com']]);
    $this->assertSession()->linkByHrefExists(Url::fromRoute('form_test.route8')->toString());
  }

}

    $this->accessManager = $this->createMock('Drupal\Core\Access\AccessManagerInterface');
    $this->accessManager->expects($this->any())
      ->method('checkNamedRoute')
      ->willReturn(AccessResult::allowed()->addCacheTags(['foo', 'bar']));

    $this->customPageSubscriber = new CustomPageExceptionHtmlSubscriber($this->configFactory, $this->kernel, $this->logger, $this->redirectDestination, $this->accessUnawareRouter, $this->accessManager);

    $path_validator = $this->createMock('Drupal\Core\Path\PathValidatorInterface');
    $path_validator->expects($this->any())
      ->method('getUrlIfValidWithoutAccessCheck')
      ->willReturn(Url::fromRoute('foo', ['foo' => 'bar']));
    $container = new ContainerBuilder();
    $container->set('path.validator', $path_validator);
    \Drupal::setContainer($container);

    // You can't create an exception in PHP without throwing it. Store the     // current error_log, and disable it temporarily.     $this->errorLog = ini_set('error_log', file_exists('/dev/null') ? '/dev/null' : 'nul');
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.