Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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'),
);
...
}
Comment | File | Size | Author |
---|---|---|---|
#2 | 1173730-fapi-reserved-values.patch | 6.42 KB | Dave Reid |
#1 | 1173730-fapi-reserved-values.patch | 6.16 KB | Dave Reid |
Comments
Comment #1
Dave ReidComment #2
Dave ReidComment #3
wjaspers CreditAttribution: wjaspers commentedWhat would your thoughts be regarding a common storage/retrieval mechanism or way to trap these between modules or to handle changes from hook_form_alter() ?
Comment #4
Dave ReidI'm just thinking support the simple use cases of an array of values for now. More complex use cases can use #element_validate and write their own validation function. Modules can easily add to these values using form alter just like any other property.
Comment #6
attiks CreditAttribution: attiks commentedsubscribing for #1239910: META: tracking other issues about validation
Comment #7
thedavidmeister CreditAttribution: thedavidmeister commented#2: 1173730-fapi-reserved-values.patch queued for re-testing.