0

I want to edit the file upload description label and the help sentence underneath it:

enter image description here

I tried the below code:

function mymodule_field_widget_form_alter(&$element, FormStateInterface &$form_state, $context) {
  if (isset($element['#field_name'] == 'field_file_description') {
      // Add process callback to change field description.
      $element['#process'][] = 'chg_desc';
    }
  }
}

function chg_desc($element, FormStateInterface $form_state, $form) {
  $element['#description'] = t('Trying to edit desc help');
  return $element;
}

It does not have any impact on the field label and help text. How can they be changed?

1

I'm going to assume that the machine name of your file field is field_file_description.

According to FileWidget.php#L414, the description is it's own element in the form, so instead of $element['#description'] it should be $element['description']['#description']. I just tested that and it works.

Here is a working code sample:

function mymodule_field_widget_form_alter(&$element, FormStateInterface &$form_state, $context) {
  if (!array_key_exists('#field_name', $element)) {
    return;
  }
  if ($element['#field_name'] == 'field_file_description') {
    // Add process callback to change field description.
    $element['#process'][] = 'mymodule_process_field_file_description';
  }
}

function mymodule_process_field_file_description($element, FormStateInterface $form_state, $form) {
  $element['description']['#title'] = t('Help!!!');
  $element['description']['#description'] = t('Trying to edit desc help');
  return $element;
}
1
  • Thank you so so much for this help. the machine name for my field was field_attachment. changing that, worked out the magic for me!
    – chaydru
    Nov 13 '21 at 22:41

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.