How can I use the core link field widget with title and URL in a custom form? I want to add a link field to my custom form.

Below is the code that I have been trying to use but no success. So can anyone let me know how to use core link field in a custom form in Drupal8?

The below code works for Drupal7 but not for Drupal8. I have also tried using #type => 'link' in the below code.

$form['cta'] = [
  '#type' =&gt; 'link_field',
  '#field_name' =&gt; 'link_field',
  '#field_parents' =&gt; array(),
  '#delta' =&gt; 0,  
];
return $form;
I think you have to create two seperate form fields to do this in Drupal 8.

You can use textfield for the title and url for the URL field, like this:

$form['cta_title'] = [
  '#type' =&gt; 'textfield',
  '#title' =&gt; t('CTA Title'),
];

$form['cta_url'] = [
  '#type' =&gt; 'url',
  '#title' =&gt; t('CTA Url'),
];

return $form;


Another solution is to pull the widget out from an entity display. There is a guide how to do that here, https://www.webomelette.com/how-render-entity-field-widgets-inside-custom-form-drupal-8.

Basically you load the entity display,

$entity = $this-&gt;entityTypeManager-&gt;getStorage('node')-&gt;create(['type' =&gt; 'article']);
$form_display = $this-&gt;entityTypeManager-&gt;getStorage('entity_form_display')-&gt;load('node.article.custom_form_display');


And then you pull out the widgets and add them to your form,

foreach ($form_display-&gt;getComponents() as $name =&gt; $component) {
  $widget = $form_display-&gt;getRenderer($name);
  if (!$widget) {
    continue;
  }

  $items = $entity-&gt;get($name);
  $items-&gt;filterEmptyItems();
  $form[$name] = $widget-&gt;form($items, $form, $form_state);
  $form[$name]['#access'] = $items-&gt;access('edit');
}