A common issue that developers face in Drupal is changing the 'Name' label on term add/edit pages. This label is used to identify the name of the term being added or edited and is an important aspect of the user experience.
The Solution
The solution to changing the 'Name' label on term add/edit pages in Drupal 10 is quite simple. All you need to do is implement the hook_form_alter()
function in your custom module and use the following code:
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'taxonomy_MYVOCABULARY_form') {
$form['name']['#title'] = t('New Title');
}
}
In the code above, we are using the hook_form_alter()
function to alter the form with the ID taxonomy_MYVOCABULARY_form
. The $form['name']['#title']
line is used to change the title of the 'Name' label to the string 'New Title'
. The t()
function is used to translate the string into the language used by the site.
It's important to note that in some cases, the 'Name' label may be a widget instead of a form item. In this case, the solution is slightly different:
/**
* Implements hook_form_alter().
*/
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'taxonomy_MYVOCABULARY_form') {
$form['name']['widget'][0]['value']['#title'] = t('New Title');
}
}
In the code above, we are using the same hook_form_alter()
function, but this time we are targeting the widget associated with the 'Name' label. The $form['name']['widget'][0]['value']['#title']
line is used to change the title of the widget to the string 'New Title'
.