0

If we want to alter webform item e.g. add a colon : to a label of a specific field, we use this:

$form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";

But what if we want to apply that colon to all field labels and not just that one my_form_component?

Current code:

function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
  if (strpos($form_id, 'webform_client_form_') === 0) {
    $form['submitted']['my_form_component']['#title'] = $form['submitted']['my_form_component']['#title'] . ":";
  }
}

1 Answer 1

1
+50

You should be able to do it with a recursive function, looping through the render array and adding a colon to any elements that have a #title element.

function addColonsToTitles(&$element) {
  if (isset($element['#title'])) {
    $element['#title'] .= ':';
  }

  foreach (element_children($element) as $index) {
    addColonsToTitles($element[$index]);
  }
}

function MYTHEME_form_alter( &$form, &$form_state, $form_id ){
  if (strpos($form_id, 'webform_client_form_') === 0) {
    addColonsToTitles($form['submitted']);
  }
}
2
  • This solves it, but I also expected for the colons to appear in emails. They actually appear by default, but toggling HTML setting for emails in Webforms for some reason strips colons. Anyway, thanks. Commented Feb 6, 2023 at 23:35
  • You asked how to change form labels. The labels in the email will not be form labels, and the manner of adding colons would be entirely different. You can open a new issue for that.
    – Jaypan
    Commented Feb 7, 2023 at 0:22

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.