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.
Here's a style plugin validator function that checks for the presence of specific fields.
To specify which fields are need, add a key to the style plugin definition of the form:
'required_fields' => array('field_machine_name_1', 'field_machine_name_2'),
/**
* Validate a view for specific fields.
* Add a key to the style plugin definition of the form:
* 'required_fields' => array('field_machine_name_1', 'field_machine_name_2'),
*/
function views_plugin_validate_required_fields($type, $view, $form) {
$plugins = _views_get_style_plugins();
$plugin_id = $type == 'page' ? $view['page_type'] : $view['block_type'];
if (is_array($plugins[$plugin_id]['required_fields'])) {
// build a list of fieldnames
$id = 0;
while (is_array($view['field'][$id]) ) {
$fieldnames[$view['field'][$id]['field']] = TRUE;
$id++;
}
foreach ($plugins[$plugin_id]['required_fields'] as $required_field) {
dsm($fieldnames);
if (!$fieldnames[$required_field]) {
form_error($form["$type-info"][$type . '_type'],
t('The @style style requires the field @field.', array(
'@style' => $plugins[$plugin_id]['name'],
'@field' => $required_field,
)
));
}
}
}
}
Possible improvements: this gives the machine name in the error message. It would be better to get the field's human-readable name out of views data so the user has a better clue of what they need to find in the field drop-down to fix the problem.