You are here

function entityreference_autocreate_field_widget_form_alter in Entityreference Autocreate 7

Adjust the behaviour of entityreference autocomplete widgets.

Replaces the normal validation that prevents linking to imaginary entities with our own, which makes it on the fly if needed.

hook_field_widget_form_alter()

File

./entityreference_autocreate.module, line 140
Intercepts entityreference autocomplete submission validation and creates a target node on the fly if it doesn't yet exist.

Code

function entityreference_autocreate_field_widget_form_alter(&$element, &$form_state, $context) {

  // First check if we are relevant or needed on this field widget.
  if ($context['field']['type'] != 'entityreference') {
    return;
  }
  if (empty($context['instance']['widget']['settings']['entityreference_autocreate']['active'])) {
    return;
  }

  // We are an autocomplete. What's the details?
  $target_bundle = entityreference_autocreate_get_target_bundle($context['field']);
  $title = t('Autocreate enabled - any title put here will cause a "!bundle" to be created if no autocomplete match is found.', array(
    '!bundle' => $target_bundle,
  ));

  // So adjust the form field now.
  if ($context['instance']['widget']['type'] == 'entityreference_autocomplete') {

    // If it's autocomplete standard, there is a 'target_id'
    $element['target_id']['#attributes']['title'] = $title;
    $element['target_id']['#entityreference_autocreate_settings'] = $context['instance']['widget']['settings']['entityreference_autocreate'];

    // To bypass the normal validation, need to REPLACE it totally.
    $element['target_id']['#element_validate'] = array(
      'entityreference_autocreate_validate',
    );
  }
  if ($context['instance']['widget']['type'] == 'entityreference_autocomplete_tags') {

    // If it's autocomplete tags style ..
    $element['#attributes']['title'] = $title;
    $element['#entityreference_autocreate_settings'] = $context['instance']['widget']['settings']['entityreference_autocreate'];

    // To bypass the normal validation, need to REPLACE it totally.
    $element['#element_validate'] = array(
      'entityreference_autocreate_validate_tags',
    );
  }
}