You are here

function relation_add_save in Relation add 7

Submit handler for the save button.

1 string reference to 'relation_add_save'
relation_add_block_block_form in modules/relation_add_block/relation_add_block.module
The relation add block form.

File

modules/relation_add_block/relation_add_block.module, line 231
Relation Add Block module file.

Code

function relation_add_save($form, &$form_state) {
  $type_array = explode(':', $form_state['values']['relation_type']);
  $type = $type_array[0];

  // Entity_form_submit_build_entity() uses this later,
  // so set it to the correct value.
  $form_state['values']['relation_type'] = $type;

  // Gather all the endpoint entities into one array.
  $entity_strings = array();
  for ($i = 2; $i; $i++) {
    if (isset($form_state['values']['target_' . $i])) {
      $entity_strings[] = $form_state['values']['target_' . $i];
    }
    else {

      // Break loop.
      $i = FALSE;
    }
  }

  // Add the current entity to the endpoints array.
  if ($form_state['relation_reverse']) {

    // For reverse relations, add the "current entity" to the end of the array,
    // else to the start.
    array_push($entity_strings, $form_state['relation_add']);
  }
  else {
    array_unshift($entity_strings, $form_state['relation_add']);
  }

  // Convert all entity_strings to proper entity_keys.
  $entity_keys = array();
  foreach ($entity_strings as $r_index => $entity_string) {
    $matches = array();
    preg_match('/(.*)\\[([\\w\\d]+):(\\d+)\\]/', $entity_string, $matches);
    if ($matches) {
      $entity_keys[] = array(
        'entity_label' => $matches[1],
        'entity_type' => $matches[2],
        'entity_id' => $matches[3],
        'r_index' => $r_index,
      );
    }
  }

  // @TODO: IF count(entity_keys) != count (entity_strings), FAIL.
  $relation = relation_create($type, $entity_keys);
  entity_form_submit_build_entity('relation', $relation, $form['relation_options'], $form_state);
  $rid = relation_save($relation);
  if ($rid) {
    $link = l($type, "relation/{$rid}");

    // See also _relation_stored_entity_keys_list()
    // in relation_entity_collector.module.
    $list = array(
      '#theme' => 'item_list',
      '#items' => array(),
    );
    foreach ($entity_keys as $entity_key) {
      $list['#items'][] = $entity_key['entity_label'];
    }
    $rendered_list = drupal_render($list);
    $message = t('Created new !link from !list', array(
      '!link' => $link,
      '!list' => $rendered_list,
    ));
    drupal_set_message($message);
  }
  else {
    drupal_set_message(t('Relation not created.'), 'error');
  }
}