I need to catch username/password using the hook_form_alter(). I'm using this code:

function sds_form_alter(&$form, FormStateInterface $form_state, $form_id ) {

  if (in_array($form_id, ['user_login_block_form', 'user_login_form'])) {  
    $username= $form_state->getValue('name');
    echo "Username Value".$username;


but it returns null. What am I missing here?

  • Please provide what you want to achieve by catching the username and password so we can provide better solution for your requirement. hook_form_alter is called before form is rendered. So you'll always get the username and password empty, because user has not yet entered that info in form. – Yogesh Nov 3 '16 at 5:25
  • @Yogesh . thanks for the response i want to get the username and password after the form was submitted because i want to query the username and password from other platform specifically in salesforce. Now according to you , i think im in a wrong track can you help me out of this.. thanks a lot.! – Looytawon Nov 3 '16 at 5:30

You can use in VALIDATE function like

$form['#validate'][] = 'mymodule_user_validate';

In this you can all values even if there is no successful values in it. But remember to call your function first before default validate function.

| improve this answer | |

When hook_form_alter() is invoked, the form has not been submitted yet, so you cannot get any value from $form_state. You need to add a form submission handler, and from that get the username.

$form['#submit'][] = 'mymodule_user_submit';

If you are, instead, trying to get the default value set in the form, then you should use the following code, in your hook_form_alter() implementation.

$default_name = $form['name']['#default_value'];

It would still return an empty value, since Drupal doesn't set a default value for the username, but that is the correct code to get the default value of a form element from hook_form_alter().

| improve this answer | |
  • hi @kiamlaluno , its good and working but $form['#submit'][] = 'mymodule_user_submit' bu works only if the form was successful (ie if username and pass is valid or true) but i want to catch the username and password even if it's not a authenticated user! can we do that though? – Looytawon Nov 3 '16 at 5:48
  • I did these: * add $form['#submit'][] = 'mymodule_user_submit'; in my hook_form_alter. *in my mymodule_user_submit I get the $form_state->getvalue('name or pass'). these code are working but now the problem it's only triggered and executed when the form was successful , now i'm wodering if i can get those user inputs right before the it was submitted or trigger the function mymodule_upload_enabled_types_submit even though the login is failed .! – Looytawon Nov 3 '16 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.