You are here

function redhen_relation_connection_form_submit in RedHen CRM 7

Submit handler for redhen_relation_connection_form().

File

modules/redhen_relation/includes/redhen_relation.forms.inc, line 345
Form definition and handling for redhen relations.

Code

function redhen_relation_connection_form_submit($form, &$form_state) {
  $entity = $form_state['entity'];
  $relation = $form_state['relation'];

  // Is this editing an existing relation?
  $edit = !empty($relation->rid) ? TRUE : FALSE;

  // Check if user has edit/update permission on the entity.
  $edit_access = entity_access('edit', $entity
    ->entityType(), $entity);

  // On edit of existing or creation of new entity, submit field values for related entity.
  if ($edit && $edit_access || isset($form_state['values']['new_or_existing']) && $form_state['values']['new_or_existing'] == 1) {
    $entity_to_relate = $form_state[$form_state['entity_to_relate_type']];
    field_attach_submit($form_state['entity_to_relate_type'], $entity_to_relate, $form, $form_state);

    // Attach properties.
    $entity_properties = entity_get_property_info($form_state['entity_to_relate_type']);
    foreach ($entity_properties['properties'] as $entity_property => $data) {
      if (isset($form_state['values'][$entity_property])) {
        $entity_to_relate->{$entity_property} = $form_state['values'][$entity_property];
      }
    }
    entity_save($form_state['entity_to_relate_type'], $entity_to_relate);
    list($entity_to_relate_id, , ) = entity_extract_ids($form_state['entity_to_relate_type'], $entity_to_relate);

    // If new, populate the endpoints.
    if (!$edit) {

      // Set relation.
      $endpoints = redhen_relation_endpoints($form_state['values']['relation_type'], $form_state['entity_to_relate_type'], $entity_to_relate_id, $entity);
      $form_state['values']['endpoints'][LANGUAGE_NONE] = $endpoints;
    }
  }

  // Set any necessary properties on new relations.
  if (!$edit) {
    $relation->relation_type = $form_state['values']['relation_type'];
  }
  field_attach_submit('relation', $relation, $form, $form_state);
  if (relation_save($relation)) {
    drupal_set_message(t('The connection has been saved.'));
    $uri = entity_uri($entity
      ->entityType(), $entity);
    $form_state['redirect'] = $uri['path'] . "/connections";
  }
  else {
    drupal_set_message(t('The connection could not be saved.'), 'error');
  }
}