You are here

function url_field_widget_form in URL field 7

Same name and namespace in other branches
  1. 8 url.module \url_field_widget_form()

Implements hook_field_widget_form().

File

./url.module, line 143
Provides a URL field type that stores external links with optional titles.

Code

function url_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $settings = $instance['settings'];
  $single_field = $field['cardinality'] == 1 && empty($settings['title_field']);

  // Display this element in a fieldset if there is only one value.
  if ($field['cardinality'] == 1 && !$single_field) {
    $element['#type'] = 'fieldset';
  }

  // URL field.
  $element['value'] = array(
    '#type' => 'urlfield',
    // Assumes elements module is enabled.
    '#title' => $single_field ? $element['#title'] : t('URL'),
    '#default_value' => isset($items[$delta]['value']) ? $items[$delta]['value'] : '',
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 2048,
    '#required' => !empty($element['#required']),
    '#prefix' => '<div class="field-value field-value-url">',
    '#suffix' => '</div>',
    '#description' => $single_field ? $element['#description'] : '',
  );
  if (!module_exists('elements')) {
    $element['value']['#type'] = 'textfield';
    $element['value']['#element_validate'] = array(
      'url_validate_url',
    );
  }

  // Title field.
  if (!empty($settings['title_field'])) {
    $element['title'] = array(
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#default_value' => isset($items[$delta]['title']) ? $items[$delta]['title'] : '',
      '#maxlength' => 1024,
      '#weight' => 10,
      '#prefix' => '<div class="field-value field-value-title">',
      '#suffix' => '</div>',
    );

    // Add additional styling to make both fields work together visually.
    $element['#attached']['css'][] = drupal_get_path('module', 'url') . '/url.field.css';
  }
  else {
    $element['title'] = array(
      '#type' => 'value',
      '#default_value' => isset($items[$delta]['title']) ? $items[$delta]['title'] : '',
    );
  }

  // Exposing the attributes array in the widget is left for alternate and more
  // advanced field widgets.
  $element['attributes'] = array(
    '#type' => 'value',
    '#value' => !empty($items[$delta]['attributes']) ? $items[$delta]['attributes'] : array(),
  );

  // If the widget is being used on a default value form, due to a core bug we
  // need to set the attributes default value to be an already serialized
  // value so that it saves properly.
  // @todo Remove when http://drupal.org/node/1899498 is fixed.
  if (empty($element['#entity']) && !isset($items[$delta]['attributes'])) {
    $element['attributes']['#value'] = NULL;
  }
  return $element;
}