You are here

function farm_plan_link_record in farmOS 7

Link a plan to a record.

Parameters

string $record_type: The record type (see farm_plan_record_relationships()).

int $plan_id: The plan ID.

int $record_id: The record ID.

array $primary_record: If this is not the primary/required record type in the table, the primary record key/value to needed for updating the existing record. For example: array('asset_id' => 5)

File

modules/farm/farm_plan/farm_plan.module, line 760
Farm plan - A farm plan entity type.

Code

function farm_plan_link_record($record_type, $plan_id, $record_id, $primary_record = array()) {

  // First, delete any existing link.
  farm_plan_unlink_record($record_type, $plan_id, $record_id);

  // Get available relationships between plans and other record types.
  $relationships = farm_plan_record_relationships();

  // If a database table and field are not available, bail.
  if (empty($relationships[$record_type]['table']) || empty($relationships[$record_type]['field'])) {
    return;
  }

  // Get the table and field.
  $table = $relationships[$record_type]['table'];
  $field = $relationships[$record_type]['field'];

  // If this record type is not required, and a primary key/value is provided,
  // then update the existing relationship row.
  if ($relationships[$record_type]['required'] === FALSE && !empty($primary_record)) {
    $primary_record_key = key($primary_record);
    $primary_record_id = current($primary_record);
    $record = array(
      'plan_id' => $plan_id,
      $primary_record_key => $primary_record_id,
      $field => $record_id,
    );
    $primary_keys = array(
      'plan_id',
      $primary_record_key,
    );
    drupal_write_record($table, $record, $primary_keys);
  }
  else {
    $record = array(
      'plan_id' => $plan_id,
      $field => $record_id,
    );
    drupal_write_record($table, $record);
  }
}