You are here

farm_term.module in farmOS 7

Code for the Farm Term module.

File

modules/farm/farm_term/farm_term.module
View source
<?php

/**
 * @file
 * Code for the Farm Term module.
 */

/**
 * Create a new taxonomy term or load an existing term by name.
 *
 * @param string $name
 *   The name of the term.
 * @param string $vocabulary
 *   The name of the vocabulary.
 * @param bool $create
 *   Boolean: If TRUE, a new term will be created if one does not exist.
 * @param bool $load
 *   Boolean: If TRUE, attempt to load existing terms first.
 *
 * @return object|bool
 *   Returns a taxonomy term object, or FALSE if none were loaded/created.
 */
function farm_term($name, $vocabulary, $create = TRUE, $load = TRUE) {

  // If $load is TRUE, attempt to look up existing terms.
  $terms = array();
  if ($load) {
    $terms = taxonomy_get_term_by_name($name, $vocabulary);
  }

  // If terms were found, return the first one.
  if (!empty($terms)) {
    $term = reset($terms);
    return $term;
  }
  elseif ($create == TRUE) {

    // Attempt to load the vocabulary by machine name. If it can't be loaded,
    // bail.
    $vocab = taxonomy_vocabulary_machine_name_load($vocabulary);
    if (empty($vocab)) {
      return FALSE;
    }

    // Create and save the term.
    $term = new stdClass();
    $term->name = check_plain($name);
    $term->vid = $vocab->vid;
    taxonomy_term_save($term);
    return $term;
  }
  else {
    return FALSE;
  }
}

/**
 * Parse a string of term names and return an array of loaded term entities. If
 * term names do not exist, they can optionally be created.
 *
 * @param string $names
 *   A comma-separated list of term names.
 * @param bool $create
 *   Whether or not to create terms that don't exist. Defaults to FALSE.
 *
 * @return array
 *   Returns an array of term objects. If the term names exist, they will be
 *   loaded from the database. Otherwise, they will be created.
 */
function farm_term_parse_names($names, $vocabulary, $create = FALSE) {

  // Start with an empty array.
  $terms = array();

  // Explode the value into an array and only take the first value.
  // (Same behavior as taxonomy autocomplete widget.)
  $values = drupal_explode_tags($names);

  // If the value is empty, bail.
  if (empty($values)) {
    return $terms;
  }

  // Iterate through the values and built an array of terms.
  foreach ($values as $value) {

    // Create/load the term.
    $term = farm_term($value, $vocabulary, $create);

    // Add to the array of terms.
    $terms[] = $term;
  }

  // Return the array of terms.
  return $terms;
}

Functions

Namesort descending Description
farm_term Create a new taxonomy term or load an existing term by name.
farm_term_parse_names Parse a string of term names and return an array of loaded term entities. If term names do not exist, they can optionally be created.