I'm trying to retrieve the URL and the Title values of a Link field in Drupal 8.
In my custom controller, I retrieve the nodes with:
$storage = \Drupal::entityManager()->getStorage('node');
$nids = $storage->getQuery()
->condition('type', 'partners')
->condition('status', 1)
->execute();
$partners = $storage->loadMultiple($nids);
When I loop throught all my nodes, to preprocess vars I'll give to my view, I would like to retrieve the URL and the Title.
foreach ($partners as $key => $partner) {
$variables['partners'][] = array(
'image' => $partner->field_logo->entity->url(),
'url' => $partner->field_link->value, // Can't retrieve values of link field
);
}
Unfortunately, I don't found how to retrieve the URL and the Title of field_link.
Thanks for your help.
At the node level, inside your Twig template you can use:
{{ content.field_link.0['#url'] }}
& {{ content.field_link.0['#title'] }}
For example:
<a href="{{ content.field_link.0['#url'] }}">{{ content.field_link.0['#title'] }}</a>
field_link
being the name of the link field in question.
I just found the solution ...
$partner->field_lien->uri // The url
$partner->field_lien->title // The title
My bad, hope it could help someone.
Just to piggyback on the above, if you have an external link,
$node->field_name->uri
Will give you the URL, but if it's an internal you may need to tweak a bit more:
use Drupal\Core\Url;
$mylink = Url::fromUri($node->field_name[0]->uri);
$mylink->toString();
You can render either the uri or text of a link field directly in the twig template. In the case of a node you can use either of the following within the twig template file (assumes the machine name of your link field is field_link
):
{{ node.field_link.uri }}
{{ node.field_link.title }}
Updated for Drupal 8
To get the url all you need to do is:
{{ content.field_link_name[0]['#url'] }}
To get the link text:
{{ content.field_link_name[0]['#title'] }}
This one works for me in twig:
content.field_link_name.0['#title'] // title
content.field_link_name.0['#url_title'] // url value
*you should use: "Separate link text and URL" widget in display
I am doing this link separation for ECK fields and this solution really helped me. I have updated the code for ECK fields for apply inline style in twig file like this:
<a style="color: {{ entity.field_link_color[0] }};" href="{{ entity.field_link[0]['#url'] }}"> {{ entity.field_link[0]['#title'] }} </a>
To get url:
{{ entity.field_link[0]['#url'] }}
To get link title:
{{ entity.field_link[0]['#title'] }}
After rendering a block if you want to access the link field used in it then you can use like this $render['field_target_url']['#items']->uri inside node preprocess hook.
One more way is to add another field Path:Content if you are trying to fetch the URL in Views Fields