4

Inside a custom block plugin I'm creating, I programmatically load the user form and return it like so

public function build() {
    $fb       = \Drupal::formBuilder();
    $userform = $fb->getForm("Drupal\user\Form\UserLoginForm");

    $render = [
        '#type'       => 'container',
        '#attributes' => [
            'class'      => ['row', 'expanded'],
            'id'         => ['login-page-block']
        ],
        'userlogin' => [
            '#type'    => 'html_tag',
            '#tag'     => 'h3',
            '#value'   => 'Welcome Members!',
            'caption'  => [
                '#type'   => 'html_tag',
                '#tag'    => 'p',
                '#value'  => 'To access member-exclusive content on our website, you must login.',
            ],
            'form' => $userform,
        ],
    ];

    return $render;
}

It creates labels for the inputs for Username and Password, but I'd rather ditch the labels and put 'Username' and 'Password' as placeholders inside the input fields. However I'm not sure how I would go about doing that. I performed a die(print_r($userform)); to get a list of fields in the array but I didn't see anything applying to the array.

Is there a way to place placeholder text inside the text input fields of a form that was programmatically retrieved and rendered?

UPDATE: I attempted changing the placeholder by writing

$userform['keys']['#attributes']['placeholder'] = t('Username');

But that didn't seem to do anything.

2 Answers 2

5

I was able to add the placeholder text by entering

    $userform['name']['#attributes']['placeholder'] = t('Username');
    $userform['pass']['#attributes']['placeholder'] = t('Password');

After looking at the results of die(print_r($userform)); more closely I saw that the username input was called 'name', and password was 'pass'

1

I've found this solution here that worked for me:

/**

 * Implements template_preprocess_input().

 */

function MYTHEME_preprocess_input(&$variables) {

  // Set a placeholder for all search form elements.

  if ($variables['attributes']['type'] == 'search') {

    $variables['attributes']['placeholder'] = $variables['element']['#title']; 

  }

}

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.