You are here

function aet_insert_form_alter in Advanced Entity Tokens 7

implementation of hook_form_alter

Adds AET Insert field if requested in the above form.

File

aet_insert/aet_insert.module, line 148

Code

function aet_insert_form_alter(&$form, &$form_state, $form_id) {

  // Only add this field if the user has access.
  if (user_access('use AET Insert') && isset($form['#entity']) && !empty($form_state['field'])) {
    $entity = $form['#entity'];
    $entity_type = $form['#entity_type'];
    $entity_info = entity_get_info($entity_type);
    $id_key = $entity_info['entity keys']['id'];
    $id = isset($entity->{$id_key}) ? $entity->{$id_key} : FALSE;
    $uuid = AET_INSERT_UUID && isset($entity->uuid) ? $entity->uuid : FALSE;
    $bundle_key = !empty($entity_info['budle keys']) ? $entity_info['budle keys']['bundle'] : FALSE;
    $bundle = $bundle_key && isset($entity->{$bundle_key}) ? $entity->{$bundle_key} : FALSE;
    $query = db_select('aet_insert', 'ai')
      ->fields('ai', array(
      'entity_type',
      'field_name',
    ))
      ->condition('ai.entity_type', $entity_type, '=');
    $results = $query
      ->execute();
    $field_names = array();
    foreach ($results as $result) {
      $field_names[] = $result->field_name;
    }
    foreach ($field_names as $field_name) {
      if (isset($form_state['field'][$field_name]) && !empty($form[$field_name])) {
        $lang = $form[$field_name]['#language'];
        for ($delta = 0; $delta < count($form[$field_name][$lang]) && isset($form[$field_name][$lang][$delta]); $delta++) {
          $form[$field_name][$lang][$delta]['aet_insert_field'] = array(
            '#type' => 'aet_insert_field',
            '#theme' => 'aet_insert_field',
            '#weight' => 999,
            '#target' => 'edit-' . str_replace("_", "-", $field_name) . '-' . $lang . '-' . $delta . '-value',
            '#entity_type' => $entity_type,
            "#entity_key" => $id_key,
            "#{$id_key}" => $id,
            '#bundle' => $bundle,
          );
          if ($uuid) {
            $form[$field_name][$lang][$delta]['aet_insert_field']['#entity_uuid'] = $uuid;
          }
        }
      }
    }
  }
}