You are here

function rooms_availability_reference_autocomplete_validate in Rooms - Drupal Booking for Hotels, B&Bs and Vacation Rentals 7

Validation callback for a node_reference autocomplete element.

1 string reference to 'rooms_availability_reference_autocomplete_validate'
rooms_availability_reference_field_widget_form in modules/rooms_availability_reference/rooms_availability_reference.module
Implements hook_field_widget_form().

File

modules/rooms_availability_reference/rooms_availability_reference.module, line 421
Defines a field type for referencing availability information

Code

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

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

      // Explicit nid. Check that the 'title' part matches the actual title for
      // the nid.
      list(, $title, $unit_id) = $matches;
      if (!empty($title)) {
        $unit = rooms_unit_load($unit_id);
        $real_title = $unit->name;
        if (trim($title) != trim($real_title)) {
          form_error($element, t('%name: title mismatch. Please check your selection.', array(
            '%name' => $instance['label'],
          )));
        }
      }
    }
    else {

      // No explicit unit_id (the submitted value was not populated by
      // autocomplete selection). Get the unit_id of a referenceable node from
      // the entered title.
      $options = array(
        'string' => $value,
        'match' => 'equals',
        'limit' => 1,
      );
      $references = rooms_availability_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...
        $unit_id = key($references);
      }
      else {
        form_error($element, t('%name: unable to find a unit with that title.', array(
          '%name' => $instance['label'],
        )));
      }
    }
  }

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