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 forsetOption('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);
Comments
Great work
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.]
Out-of-date
Url::createFrompath() has been removed.