You are here

public function PowerMenuTaxonomyHandler::menuFormSubmit in Power Menu 7.2

Overrides PowerMenuHandlerInterface::menuFormSubmit

See also

PowerMenuHandlerInterface::menuFormSubmit()

File

plugins/menu_handlers/PowerMenuTaxonomyHandler.class.php, line 198

Class

PowerMenuTaxonomyHandler
Implementation of the interface PowerMenuHandlerInterface.

Code

public function menuFormSubmit(array $form, array &$form_state) {
  $terms = variable_get('power_menu_taxonomy_terms', array());
  $vocabulary = variable_get('power_menu_taxonomy_vocabulary', array(
    'vid' => NULL,
    'machine_name' => NULL,
  ));

  // Add new term if create selected
  if ($vocabulary['vid'] !== NULL && !empty($form_state['values']['power_menu_taxonomy_create'])) {

    // Does a term with this name exists
    $term_name = $form_state['values']['link_title'];
    $term = db_select('taxonomy_term_data', 't')
      ->fields('t', array(
      'tid',
    ))
      ->condition('t.name', $term_name)
      ->condition('t.vid', $vocabulary['vid'])
      ->execute()
      ->fetchField();
    if (!$term || variable_get('power_menu_taxonomy_create_term_always', FALSE)) {
      $term = new stdClass();
      $term->vid = $vocabulary['vid'];
      $term->name = $term_name;

      // Build the hierarchy based on the parent menu-item -> term association when possible
      if (!empty($form_state['values']['parent'])) {
        $mlid = explode(':', $form_state['values']['parent']);

        // Has the parent mlid an association to a term
        $parent_term = array_search($mlid[1], $terms);
        if ($parent_term) {
          $term->parent = $parent_term;
        }
      }

      // Save the term and add it to the selected terms
      taxonomy_term_save($term);
      $form_state['values']['power_menu_taxonomy_terms'][] = $term->tid;
    }
  }
  if (isset($form_state['values']['power_menu_taxonomy_terms'])) {
    $selected_terms = $form_state['values']['power_menu_taxonomy_terms'];
    $mlid = $form_state['values']['mlid'];

    // First delete all used terms with given mlid
    foreach ($terms as $key => $value) {
      if ($value == $mlid) {
        unset($terms[$key]);
      }
    }

    // Add new selected terms with this mlid
    foreach ($selected_terms as $value) {
      $terms[$value] = $mlid;
    }
  }
  variable_set('power_menu_taxonomy_terms', $terms);
}