You are here

function block_machine_name_validate in Block Machine Name 7

Validate machine name.

1 string reference to 'block_machine_name_validate'
block_machine_name_form_alter in ./block_machine_name.module
Implements hook_form_alter(). @todo - Alter various block forms to add our field elements or submit/validate handlers

File

./block_machine_name.module, line 92

Code

function block_machine_name_validate($form, &$form_state) {

  // If the user did not put in a value, don't try to validate.
  if (empty($form_state['values']['machine_name'])) {
    return;
  }

  // We need to know the module of this block to manage a machine name. If we couldn't gather this, warn the
  // user that their machine name will not be saved.
  if (empty($form_state['values']['module'])) {
    drupal_set_message('Block machine name could not find all required information in the form, your machine name will not be saved.', 'warning');
    return;
  }
  $delta = $form_state['values']['delta'];
  $module = $form_state['values']['module'];
  $machine_name = $form_state['values']['machine_name'];

  // Check for invalid characters
  if (!preg_match('!^[a-z0-9_]+$!', $machine_name)) {
    form_set_error('machine_name', t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
    return;
  }

  // Query to see if any blocks are already using this machine name
  $table = 'block_machine_name_boxes';
  $query = db_select($table)
    ->condition('machine_name', $machine_name, '=');

  // If this is an existing block, exclude it from the query so we don't think the name is already in use.
  if (!empty($delta)) {
    $query
      ->condition('delta', $delta, '<>')
      ->condition('module', $module, '<>');
  }

  // Run the query
  $count = $query
    ->countQuery()
    ->execute()
    ->fetchField();
  if ($count > 0) {
    form_set_error('machine_name', t('The machine-readable name has been taken. Please pick another one.'));
  }
}