0

I would like to had a field link in a custom block. Here is my code to do that :

public function blockForm($form, FormStateInterface $form_state) {

$form['key_1'] = [
    '#title' => $this->t('Key 1 label'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#required' => false,
];

$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'link',
];

return $form;

} Now, when I go in admin/structure/block/manage/myblock, I can see my key 1 field. The key 2 is not render. If I change the type for any other (textfield, textarea, file_managed) my field is properly render. The default link module is enabled.

Is the link field type only usable in node form ? I can understand why.

1 Answer 1

3

You should add the field from the Block Type interface. Either add to the block type that comes with core or create a new one and add your fields.

Also, no, Drupal Fields and Form API elements are two different constructs. That is why 'link' does nothing. It would simply be:

$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'url',
];

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Url.php/class/Url/8.2.x

But you're creating more work that necessary.

In this context (a form) link pertains to a RenderElement and not a FormElement like url is.

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.