Using Drupal 8 File Field and enabling the optional description field works normal.

I want to have a default value populated for the field using tokens from other fields in the content type (to create a standard formatted description). Is there a way to enable this or must I disable this field and override the twig for the content type to display the desired description for the file link?

Note that this question pertains the optional description field (not the filename - that works perfectly well with the tokens using File (Field) Paths module.)


Good news - it's not that hard! Here's what you need to do:

  1. Install Drupal Console (if you haven't already): https://drupalconsole.com/
  2. Install the devel module: https://www.drupal.org/project/devel
  3. Enable the webprofiler module (part of devel) drush en webprofiler
  4. Webprofiler adds a toolbar to the bottom of your browser window. Use this to get the form ID of the form you want to modify.
  5. Use Drupal Console to generate a hook_form_FORM_ID_alter() function. You'll need either a custom theme or a custom module for this.
    • Warning: If you're modifying the node edit form, it probably uses the admin theme. You probably don't have a custom admin theme, so you may want to put this in a custom module.
  6. Customize your function to prepopulate the field the way you want. Here's what I did:

    use Drupal\Core\Form\FormStateInterface;
     * Implements hook_form_FORM_ID_alter() on behalf of coit_customizations.module.
     * Provides a default for file description on meeting edit form
    function coit_customizations_form_node_meeting_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      // Check to see if there's already a file description
      $existing_description = $form['field_supporting_documents']['widget'][0]['#default_value']['description'];
      // If there isn't, add the default
      $new_description = $existing_description ? $existing_description : 'Download Supporting Documents';
      $form['field_supporting_documents']['widget'][0]['#default_value']['description'] = $new_description;
  7. Don't forget to enable your module!

For further reading:

One last tip: xdebug is very useful for inspecting your form array so you know what to customize. If you're trying to do this kind of thing and aren't using xdebug, I recommend you check it out.

As an easier alternative, just add this to your function: drupal_set_message($form);

  • Thanks, that is quite a bit to digest. I will try it out. – George Houpis Jan 10 '18 at 22:37

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.