Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

In Drupal 7, an array containing 'path' and 'options' was often used to represent a URL, and was passed to the url() function:

$url_info = array(
  'path' => 'node/' . $node->nid;
  'options' => array(
    'fragment' => 'main-content',
  ),
);
$url = url($url_info['path'], $url_info['options']);

When representing internal paths, in Drupal 8 a route name and route parameters are used instead of a path.
But instead of building up an array and having code like \Drupal::l(t('Some text'), $url_info['route_name'], $url_info['route_parameters'], $url_info['options']);, we now have a dedicated Url class:

$url_info = new Url('node.view', array('node' => $node->id()), array('fragment' => 'main-content'));
$url = $url_info->toString();

In addition to creating a Url object manually, there are two helper methods:

$path = 'node/2/edit';
$url = Url::createFromPath($path);

$request = \Drupal::request();
$url = Url::createFromRequest($request);

Once created, the Url class has several methods to manipulate and retrieve its data:

To use with options like fragment, query, absolute

  • getOptions()
  • getOption()
  • setOptions()
  • setOption()
  • setAbsolute() (a shortcut for setOption('absolute', TRUE)

To return the internal data:

  • toArray()
  • toRenderArray() (returns with keys prefixed by '#'
  • toString() (the full URL as a string)
  • getInternalPath (without prefixes or fragments or query strings)

Example usages

In form submission methods:

$form_state->setRedirect('a_route_name', array('route' => 'parameters'), array('some' => 'options'));
//OR
$url = new Url('a_route_name', array('route' => 'parameters'), array('some' => 'options'));
$form_state->setRedirectUrl($url);

When extending \Drupal\Core\Form\ConfirmFormBase:

public function getCancelUrl() {
  return new Url('a_route_name', array('route' => 'parameters'), array('some' => 'options'));
}

When using the link generator:

$link = \Drupal::linkGenerator()->generate(t('Some text'), $url_object);
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done

Comments

almaudoh’s picture

Great work!! I love this - DX+++

[Edit: I've fiddled around a lot with $form_state['redirect_route'] recently and the DX wasn't very nice. Great to know this is in now. Thanks.]

mradcliffe’s picture

Url::createFrompath() has been removed.