5

Is there any way to prevent deleting a taxonomy term if it used in any node ?

I have a Taxonomy that is used in Field Collection in my Content Type , I want to warn/prevent deletion of any Term in that Taxonomy if it is used in any node.

I checked taxonomy_term_confirm_delete it is where the confirmation message is formed, I read from some posts about using

db_query("SELECT COUNT(nid) FROM {taxonomy_index} WHERE tid = :aid", array(':aid' => $tid) )->fetchField()

to get the number of nodes a term is used in but this is not working in my case -maybe because the taxonomy is in field collection ?

  • If it's a field collection, you could query the field_data_field_term_reference table for that entity's term reference field instead. – David Thomas Sep 8 '14 at 3:36
6

I wrote an article tackling this problem.

In short, you have to use hook_form_alter on the form taxonomy_form_term and use the function taxonomy_select_nodes() to check if a node uses the term in question.

You can just go ahead and copy the code from the article into your custom module (naming the 'mymodule_form_alter' accordingly to your module's name), flush the caches and that should do it.

1

I think you can use taxonomy_select_nodes function to achieve this.

Return nodes attached to a term across all field instances.

taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'))

Parameters

$tid: The term ID.

$pager: Boolean to indicate whether a pager should be used.

$limit: Integer. The maximum number of nodes to find. Set to FALSE for no limit.

$order: An array of fields and directions.

  • i am getting an empty array as a result eventhough my term is used in one node. the taxonomy is in a field collection, does that make any difference ? – Moh Sakkijha May 27 '14 at 10:12
  • Drupal 8 no longer has taxonomy_select_nodes so you'll want to load the nodes using entityQuery. – mpp Aug 24 '17 at 8:10
0

For Drupal 8.

Prevent Term Delete module is built to prevent the taxonomy term deletion when the taxonomy term is associated with nodes or entities using taxonomy term reference.

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.