3

I've created a module with a custom block that extends BlockBase. To the block form I added multiple textfields and select boxes, by simply specifying the formatter in the '#type' configuration.

My next step is to add a button that links to internal/external content and I've tried adding different types, such as 'link' but without any luck.

I found LinkFormatter, but I can't figure out how to use it properly with block forms.

What has to be added to the blockForm method in order to create a link field (just like the link field that's selectable within a custom block type): UI showing available link options Field options for link

My current code:

public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'link',
    '#title' => $this->t('Link title'),
    '#url' => 'Hmm?',
    '#options' => ['external' => TRUE]
  ];

  return $form;
}
4
  • The code has nothing to do with the screenshot. The code tries to output an "<a href..." html tag. The screenshot contains two text inputs to enter a link. The first text input has a database lookup. If you want this input and no output, you have to define these inputs in code, where do they come from and how to submit them.
    – 4uk4
    Commented Sep 29, 2015 at 8:40
  • I changed some details in the question. What I want is the "Link" field that's available on custom block types.
    – estrar
    Commented Sep 29, 2015 at 10:18
  • The code you are looking for is here: core/modules/link/src/Plugin/Field/FieldWidget/LinkWidget.php
    – 4uk4
    Commented Sep 29, 2015 at 15:04
  • I posted a solution for a related question: drupal.stackexchange.com/questions/213472/… Commented Nov 22, 2018 at 19:08

2 Answers 2

0

You want to change '#type' => 'link' to '#type' => 'url'

public function blockForm($form, FormStateInterface $form_state) {
  //...
  $form['link'] = [
    '#type' => 'url',
    '#title' => $this->t('Link title'),
    '#options' => ['external' => TRUE]
  ];

  return $form;
}
1
  • 1
    This will only result in a <input type="url"> and not the desired result shown in the screenshot.
    – estrar
    Commented Jan 25, 2016 at 10:49
0

You should try this code:

$form['group1'] = array(
  '#type' => 'fieldset',
  '#title' => $this->t('Link Field'),
  '#collapsible' => FALSE,
  '#collapsed' => FALSE,  
);

$form['group1']['url'] = array(
  '#type' => 'url',
  '#title' => $this->t('URL'),
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
);

$form['group1']['label'] = array(
  '#type' => 'textfield',
  '#title' => $this->t('Link Text'),
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.