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.
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.
This one works for me in twig:
*you should use: "Separate link text and URL" widget in display
Just to piggyback on the above, if you have an external link,
Will give you the URL, but if it's an internal you may need to tweak a bit more:
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
):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'] }}
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.