简体   繁体   中英

Alter Form Label using Regex in Drupal 8

I have some form fields that look like this: "Yes (if "Yes", skip the next question)" and I'd like to have any labels with text inside parenthesis be wrapped in a span so they can be styled. I tried writing a preprocess but it's not doing anything.

function THEME_preprocess_form_element_label(&$variables){
  $element = $variables['element'];
  $title = $element['#title'];
  $pat = "/\((.*?)\)/";
  if (isset($title) && preg_match($pat, $title)) {
    $titleSplit = preg_split($pat, $title);
    $newTitle = $titleSplit[0]+"<span>"+$titleSplit[1]+"</span>";
    $title = $newTitle;
  }
}

$title = $newTitle; is setting the $title variable in the function, but not on the &$variables that is passed by reference.
try:

function THEME_preprocess_form_element_label(&$variables){
  $pat = "/\((.*?)\)/";
  if (isset($variables['element']['#title']) && preg_match($pat, $variables['element']['#title'])) {
    $titleSplit = preg_split($pat, $variables['element']['#title']);
    $newTitle = $titleSplit[0]+"<span>"+$titleSplit[1]+"</span>";
    $variables['element']['#title'] = $newTitle;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM