Add #reserved_values property to Form API elements to disallow reserved values

Created on 31 May 2011, over 13 years ago
Updated 28 January 2025, 26 days ago

A common problem we're running into with machine names in D7 is that we have to add validation for certain pre-defined 'reservered' names that would conflict with system paths. I think it would be nice if we could just add a #reserved_values array property to any form API input element that would validate if the form element's value is not one of the reserved values.

For example:

function taxonomy_form_vocabulary($form, &$form_state, $edit = array()) {
  ...
  $form['machine_name'] = array(
    '#type' => 'machine_name', 
    '#default_value' => $vocabulary->machine_name, 
    '#maxlength' => 255, 
    '#machine_name' => array(
      'exists' => 'taxonomy_vocabulary_machine_name_load',
    ),
  );
  ...
}

function taxonomy_form_vocabulary_validate($form, &$form_state) {
  // During the deletion there is no 'machine_name' key
  if (isset($form_state['values']['machine_name'])) {
    // Do not allow machine names to conflict with taxonomy path arguments.
    $machine_name = $form_state['values']['machine_name'];
    $disallowed = array('add', 'list');
    if (in_array($machine_name, $disallowed)) {
      form_set_error('machine_name', t('The machine-readable name cannot be "add" or "list".'));
    }
  }
}

Becomes simply:

function taxonomy_form_vocabulary($form, &$form_state, $edit = array()) {
  ...
  $form['machine_name'] = array(
    '#type' => 'machine_name', 
    '#default_value' => $vocabulary->machine_name, 
    '#maxlength' => 255, 
    '#machine_name' => array(
      'exists' => 'taxonomy_vocabulary_machine_name_load',
    ),
    '#reserved_values' => array('list', 'add'),
  );
  ...
}
✨ Feature request
Status

Postponed: needs info

Version

11.0 πŸ”₯

Component

forms system

Created by

πŸ‡ΊπŸ‡ΈUnited States dave reid Nebraska USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States smustgrave

    Thank you for sharing your idea for improving Drupal.

    We are working to decide if this proposal meets the Criteria for evaluating proposed changes. There hasn't been any discussion here for over 8 years which suggests that this has either been implemented or there is no community support. Your thoughts on this will allow a decision to be made.

    Since we need more information to move forward with this issue, the status is now Postponed (maintainer needs more info). If we don't receive additional information to help with the issue, it may be closed after three months.

    Thanks!

Production build 0.71.5 2024