You are here

function entityqueue_widget_dragtable_element_validate in Entityqueue 7

Element validate callback.

See also

entityqueue_field_widget_form()

1 string reference to 'entityqueue_widget_dragtable_element_validate'
entityqueue_field_widget_form in ./entityqueue.module
Implements hook_field_widget_form().

File

./entityqueue.module, line 1134
Allows users to collect entities in arbitrarily ordered lists.

Code

function entityqueue_widget_dragtable_element_validate($element, &$form_state) {
  $items = array();
  $value_key = $element['#value_key'];
  $field_name = $element['#field_name'];
  $lang = $element['#language'];
  if (isset($form_state['values'][$field_name][$lang]['items'])) {
    $existing_values = $form_state['values'][$field_name][$lang]['items'];
  }
  else {
    $existing_values = array();
  }

  // Determine which button has been clicked.
  $triggering_element = $form_state['triggering_element'];
  $triggering_key = end($triggering_element['#array_parents']);
  $triggering_field = reset($triggering_element['#array_parents']);

  // Remove an item from the queue through the Remove button.
  if ($triggering_field === $field_name && $triggering_key === 'remove') {
    $remove_key = $triggering_element['#array_parents'][3];
    unset($existing_values[$remove_key]);
    $form_state['entityqueue_changed'] = TRUE;
  }
  $values = array();
  $weights = array();
  foreach ($existing_values as $key => $row) {
    $values[] = $row[$value_key];
    $weights[] = $row['weight'];
  }
  array_multisort($weights, SORT_ASC, $existing_values);
  foreach ($existing_values as $key => $row) {
    $items[] = array(
      $value_key => $row[$value_key],
    );
  }

  // Add new items to the queue.
  $new_value = $form_state['values'][$field_name][$lang]['add'];
  if ($triggering_field === $field_name && $triggering_key === 'add' && !empty($new_value['entity'])) {
    if ($element['#add_position'] === 'top') {
      array_unshift($items, array(
        $value_key => $new_value['entity'],
      ));
    }
    else {
      $items[] = array(
        $value_key => $new_value['entity'],
      );
    }
    $form_state['entityqueue_changed'] = TRUE;
  }
  form_set_value($element, $items, $form_state);

  // Rebuild form if ajax callback button was clicked.
  if (current_path() == 'system/ajax' && $triggering_element['#ajax']['callback'] == 'entityqueue_field_widget_ajax_callback') {
    $form_state['rebuild'] = TRUE;
  }
}