1

I have a site where I have a taxonomy term. I want to set a default value to the term name and display it when the form loads. In hook_form_alter(), I tried to set the default value to Check term name in the form. The form loads with this value, but even after changing the value in the text field, the form gets submitted with Check term name.

This is the code I am using to set the default value.

$form['name']['widget'][0]['value']['#value'] = 'check term name';

How do I set the default value?

3
  • 4
    You can't set #value, it should be #default_value.
    – Kevin
    Mar 29, 2022 at 14:25
  • But how come user can see this default value in the form? I want to prepopulate the title field with something and change the value according to what the user provides. Mar 29, 2022 at 14:29
  • 3
    That's exactly what default values are for, is there a reason you can't use them?
    – Clive
    Mar 29, 2022 at 14:45

1 Answer 1

0

As @Kevin and @Clive noted, you must use #default_value to do this.

$form['name']['widget'][0]['value']['#default_value'] = 'check term name';

[Property] #default_value:

Description: The value of the form element that will be displayed or selected initially if the form has not been submitted yet. Should NOT be confused with #value, which is a hard-coded value the user cannot change!

Source: Form API Reference

(Yes, this is a reference page for D7, but this section still applies.)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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