0

I need to alter the "Embed Link" form provided by Drupal 8 in the node AddForm. Namely I need to add a select list form item to specify the "type" of the embed link.

For this I am trying to implement a hook_form_alter()

  if(isset($form['field_link_embed'])){
   $form['field_link_embed']['widget']['format'] = [
    '#type' => 'select',
    '#required' => TRUE,
    '#title' =>t("Link format"),
    '#options' => [
        'open' => t("option1"),
        'html' => t("option2"),
    ]
  ];

But I guess this is not the right chain how to access the form $form['field_link_embed']['widget']['format'], could you please help me?

  • Are you trying to specify format for the Link Text or are you trying to make the Link Text a select box ? – GiorgosK Feb 18 at 13:55
  • I am trying to extend it with select box. So to say to add one more field – user91143 Feb 18 at 14:17
0

Here is quick and dirty hook_form_alter implementation that does this

Add this to your THEMENAME.theme or your MODULENAME.module

function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "node_article_edit_form" || $form_id == "node_article_form") {
    $link_count = intval($form["field_link_embed"]["widget"]["#max_delta"]);
    for ($i = 0; $i <= $link_count; $i++) {
      if (isset($form["field_link"]["widget"][$i]["format"])) {
        continue;
      }
      $form["field_link"]["widget"][$i]["format"] = [
        '#type' => 'select',
        '#required' => TRUE,
        '#title' => t("Link format"),
        '#options' => [
          'open' => t("option1"),
          'html' => t("option2"),
        ],
      ];
    }
  }
}

NOTE: you have to modify node_article_form and node_article_edit_form and perhaps field_link_embed to match your setup.

Perhaps for more involved implementation you should create a dedicated field_formatter using web/core/modules/link/src/Plugin/Field/FieldFormatter/LinkFormatter.php as a starting point.

  • Will it create a column in database? – user91143 Feb 18 at 14:55
  • Nope that is why I said its a quick and dirty solution, the use case of the above solution is ruther limited, and you actually never mentioned in your description that this is a requirement. – GiorgosK Feb 18 at 14:57
  • Sure, it is. I am sorry. Do I need to open a new question for it? – user91143 Feb 18 at 14:58
  • yeah I suppose this is the best way, as this is probably a complete question/answer already – GiorgosK Feb 18 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy