I noticed that when i use tokens as default values for form fields, the tokens are not cleared if no value was found. For example, my logged in users first name, last name etc is filled in as expected in the form fields, but when an anonymous user view the form the tokens are displayed as plain text, because no values were found.

It seems like you have to set a 'clear' flag in the options array for Token::replace to make this happen.

In YamlFormElementBase.php, in the prepare() function, this seems to solve the issue for me:

$token_options = [
  'clear' => TRUE,
];
foreach ($element as $element_property => $element_value) {
  // Most strings won't contain tokens so lets check and return ASAP.
  if (is_string($element_value) && strpos($element_value, '[') !== FALSE) {
    $element[$element_property] = \Drupal::token()->replace($element_value, $token_data, $token_options);
  }
}

Maybe this flag is needed in more places as well.

Comments

JockeL created an issue. See original summary.

jrockowitz’s picture

Using clear options makes perfect sense to me. If you post a patch and it passes all automated tests I will commit it ASAP.

JockeL’s picture

Assigned: Unassigned » JockeL
JockeL’s picture

StatusFileSize
new896 bytes
JockeL’s picture

Status: Active » Needs review
jrockowitz’s picture

@Jockel Patch looks good.

Can you please update your patch to fix all token replacements.

You just need to search for token->replace( in the code.

Thanks.

JockeL’s picture

jrockowitz’s picture

Status: Needs review » Fixed
jrockowitz’s picture

@JockeL Thanks and congrats on your first commit credit.

JockeL’s picture

Awesome, thanks!

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.