You are here

function slickgrid_prevent_duplicate_terms in Slickgrid 7.2

Due to the fact that we validate all forms at once, and then submit all forms at once, we can end up with multiple new terms, when only one is required. This function helps remedy that issue.

1 call to slickgrid_prevent_duplicate_terms()
slickgrid_editor_form_submit in ./slickgrid.module

File

./slickgrid.module, line 544

Code

function slickgrid_prevent_duplicate_terms($entity) {

  // Get the names of all taxonomy fields
  $field_names = db_select('field_config', 'f')
    ->fields('f', array(
    'field_name',
  ))
    ->condition('module', 'taxonomy')
    ->execute()
    ->fetchCol();
  foreach ($field_names as $field_name) {
    if (isset($entity->{$field_name})) {
      foreach (array_keys($entity->{$field_name}) as $lang) {
        foreach ($entity->{$field_name}[$lang] as $key => $value) {
          if (isset($value['tid']) && $value['tid'] == 'autocreate') {

            // We try and load the term, as it may now exist.
            $new = db_select('taxonomy_term_data', 'td')
              ->fields('td', array(
              'tid',
            ))
              ->condition('name', $value['name'])
              ->condition('vid', $value['vid'])
              ->execute()
              ->fetchField();
            if ($new) {
              $entity->{$field_name}[$lang][$key] = (array) taxonomy_term_load($new);
            }
          }
        }
      }
    }
  }
}