5

I've build a custom field with several values. I've to make this field required. But I want to pass the validation if at least one field is filled and the last one is empty.

But my problem is Drupal warn me that the last (empty) field is required. I've thought that the hook_field_is_empty() solved the problem, but, even if return true, the form cannot be validated.

Many thanks for your help.

Implementation :

function MYMODULE_field_widget_form(...) {
    $element['address']+=[
      ...
      '#required' => $instance['required'],
    ];
    ...
}

function MYMODULE_field_is_empty($item, $field) {
    if (empty($item['address']) && empty($item['other'])) {
        return true ;
    }
    return false ;
}
Syscall
  • 19,327
  • 10
  • 37
  • 52

1 Answers1

1

To solve this problem, I've made my field not required (in the definition of the node's fields). Then, I added a callback in the #validate using the hook_form_alter(). In that callback, I test if at least one field is defined and call a form_set_error() if none is defined.

This makes sense because it's not the field itself that could know all the data of the node. But, something is a bit wrong because it's not possible to mark this field as required (e.g. asterisks).

<?php

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($formid == ...) { // a specific case
    array_unshift($form['#validate'], '_MYMODULE_validate_form') ;
  }
}

function _MYMODULE_validate_form(&$form, &$form_state) {
  if (empty($form_state['values']['field_geo'][LANGUAGE_NONE][0]['address'])) {
    form_set_error('field_geo', t('You have to define at least one address.')) ;
  }
}

?>
Syscall
  • 19,327
  • 10
  • 37
  • 52