-1

I would like to set the file description as required. I tried it with this code:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_news_homepage_edit_form') {

    $form['field_downloads']['widget'][0]['description_field']['#required'] = TRUE;
  }
}

But it didn't work. Could anyone help me?

1
  • This seems to be the right approach, see drupal.stackexchange.com/questions/216829/…, but the key description_field looks odd to me, did you check it exists in $form? Should be description, if it is named after the File field property and this is the field type the question is about.
    – 4uk4
    Oct 1, 2018 at 12:08

2 Answers 2

1

The community is working to solve this problem: https://www.drupal.org/project/drupal/issues/2320877

While this isn't the part of the Drupal core, you can do the following:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'node_news_homepage_edit_form') {
    $form['field_downloads']['widget'][0]['#process'][] = 'set_file_description_required';
  }
}

function set_file_description_required($element) {
    $element['description']['#required'] = TRUE;
    return $element;
}
2
  • Thanks for the code. Unfortunately the description field is just required after I saved the page. And if I have two downloads it just works for the first one. But I will wait for the patch. Hope it would be soon available on drupal core.
    – Zeroplexer
    Oct 1, 2018 at 14:21
  • It only works for the edit form because it checks for the edit_form id. I answered with a version that will work for any form and multivalued fields.
    – Marc
    Jul 4, 2019 at 20:03
0

Based on @DavidCzinege answer, a version that works for any form where the field appears and also for multivalued fields:

use Drupal\Core\Render\Element;

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {

  if (!empty($form['field_file']['widget'])) {

    foreach (Element::children($form['field_file']['widget']) as $el_index) {

      $form['field_file']['widget'][$el_index]['#process'][] = 'my_module_set_file_description_required';

  }

}

function my_module_set_file_description_required($element) {

  $element['description']['#required'] = TRUE;
  return $element;

};
1
  • Thanks for the code. Unfortunately I get an error: Fatal error: Cannot redeclare my_module_set_file_description_required() (previously declared in...
    – Zeroplexer
    Sep 25, 2019 at 12:34

Your Answer

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

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