1

Task

I'm trying to add the placeholder attribute to the username and password input fields of the user login block.

Problem

When I have twig debug on, the only twig file overrides list are the following.

<!-- FILE NAME SUGGESTIONS:
* input--textfield.html.twig
x input.html.twig
-->

I don't want to use either of these twig files as it would apply to every input or every textfield.

Caveat

I'm wanting to accomplish this from within my theme not a custom module. Which I'm not sure is able to be done.

3 Answers 3

3

In twig it's difficult to target a specific input field. You can do this more efficient in a form alter hook, which you can use in themes too:

mytheme.theme

function mytheme_form_user_login_form_alter(&$form, $form_state) {
  $form['name']['#placeholder'] = t('placeholder for username');
}
2
  • Can you update your answer to utilize t() please? Thank you for the help! Commented Jan 25, 2017 at 20:45
  • added t() function.
    – 4uk4
    Commented Jan 25, 2017 at 20:59
1
/**
 * Implements hook_form_alter().
 */
function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_form' ) {
    // Add placeholders.
    $form['name']['#attributes']['placeholder'] = t('Email/Mobile Number');
    $form['pass']['#attributes']['placeholder'] = t('Password');
  }
}
0

clean solution

/**
 * Implements hook_preprocess_html().
 */
function THEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $path_alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
  $path_alias = ltrim($path_alias, '/');
  $variables['attributes']['class'][] = 'path-' . \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);
}

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.