You are here

function flipping_book_reference_autocomplete_validate in Flipping Book 7

Validation callback for a flipping_book_reference autocomplete element.

1 string reference to 'flipping_book_reference_autocomplete_validate'
flipping_book_reference_field_widget_form in ./flipping_book_reference.module
Implements hook_field_widget_form().

File

./flipping_book_reference.module, line 459
Defines a field type for referencing one flipping_book from a node.

Code

function flipping_book_reference_autocomplete_validate($element, &$form_state, $form) {
  $field = field_widget_field($element, $form_state);
  $instance = field_widget_instance($element, $form_state);
  $value = $element['#value'];
  $fbid = NULL;
  if (!empty($value)) {

    // Check whether we have an explicit "[fbid:f]" input.
    preg_match('/^(?:\\s*|(.*) )?\\[\\s*fbid\\s*:\\s*(\\d+)\\s*\\]$/', $value, $matches);
    if (!empty($matches)) {

      // Explicit fbid. Check that the 'title' part matches the actual title for
      // the fbid.
      list(, $title, $fbid) = $matches;
      if (!empty($title)) {
        $real_title = db_select('flipping_book', 'f')
          ->fields('f', array(
          'title',
        ))
          ->condition('f.fbid', $fbid)
          ->execute()
          ->fetchField();
        if (trim($title) != trim($real_title)) {
          form_error($element, t('%name: title mismatch. Please check your selection.', array(
            '%name' => $instance['label'],
          )));
        }
      }
    }
    else {

      // No explicit fbid (the submitted value was not populated by autocomplete
      // selection). Get the fbid of a referencable flipping_book from
      // the entered title.
      $options = array(
        'string' => $value,
        'match' => 'equals',
        'limit' => 1,
      );
      $references = flipping_book_reference_potential_references($field, $options);
      if ($references) {

        // @todo The best thing would be to present the user with an
        // additional form, allowing the user to choose between valid
        // candidates with the same title. ATM, we pick the first
        // matching candidate...
        $fbid = key($references);
      }
      else {
        form_error($element, t('%name: found no valid flipping_book with that title.', array(
          '%name' => $instance['label'],
        )));
      }
    }
  }

  // Set the element's value as the flipping_book id that was extracted
  // from the entered input.
  form_set_value($element, $fbid, $form_state);
}