Drupal Answers Asked by Sugandh Khanna on December 26, 2021
How do I validate the term title in hook_taxonomy_term_presave()
?
Is there a way to proceed with the validations in hook_taxonomy_term_presave()
?
@Edit
I rendered taxonomy add term form via “Inline Entity Form” module and here form_alter fails when it comes to validation.
Any other way if hook_entity_presave can’t do this?
hook_taxonomy_term_presave()
is not thought for validating anything. In fact, it doesn't have any way to stop Drupal from saving the taxonomy term, nor show an error to the users and allow them to enter the correct value. That is what a validation handler would do.
To add a validation handler for the form to edit a taxonomy term, you do as with other forms: You use hook_form_alter()
to add a new validation handler to that form, whose ID is taxonomy_form_term.
As with other forms, you can also add a validation handler that would be called only when the taxonomy term is going to be saved, which is preferable, since the form to edit a taxonomy term can also be used to delete it.
In this case, you just add the validation handler to $form['actions']['submit']
, e.g. with code similar to the following.
function mymodule_form_taxonomy_form_term_alter(&$form, &$form_state) {
$form['actions']['submit']['#validate'][] = 'mymodule_taxonomy_form_term_validate';
}
You could also use the following code, but it would try to validate the term title even when the taxonomy term is going to be deleted, which probably not something you want.
function mymodule_form_taxonomy_form_term_alter(&$form, &$form_state) {
$form['name'][#element_validate][] = 'mymodule_taxonomy_form_term_title_validate';
}
function mymodule_taxonomy_form_term_title_validate($element, &$form_state, $form) {
// Use $element['#value'] to get the submitted value.
// Use form_error($element, $error_message) to show the error to users.
}
Answered by apaderno on December 26, 2021
I assume you should be looking at hook_form_FORM_ID_alter instead of hook_taxonomy_term_presave for validating the term title before saving.
/**
* Implements hook_form_FORM_ID_alter().
**/
function mymodule_form_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
// Check for tags bundle.
if($form['#bundle'] == 'tags') {
// Apply custom validator.
$form['#validate'][] = '_mymodule_custom_term_validator';
}
}
My custom validator.
/**
* My custom validator for tags.
**/
function _mymodule_custom_term_validtor() {
// Check for term name is test.
if(form_state['values']['name'] == 'test') {
form_set_error('name', 'Title cannot be "test"');
}
}
Answered by sarathkm on December 26, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP