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'),
);
...
}
Comments
Comment #1
dave reidComment #2
dave reidComment #3
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 commentedsubscribing for #1239910: META: tracking other issues about validation
Comment #7
thedavidmeister commented#2: 1173730-fapi-reserved-values.patch queued for re-testing.
Comment #22
smustgrave commentedThank 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!
Comment #23
smustgrave commentedSince there's been no follow up in 3 months going to close out, but don't worry if still valid it can be reopened. Thanks all!