You are here

function webform_validate_grid in Webform 7.4

Element validation for Webform grid fields.

Requires a component implementation because the default required validation passes when at least one value is supplied, rather than every value. This makes the server validation match the browser validation.

1 string reference to 'webform_validate_grid'
_webform_render_grid in components/grid.inc
Implements _webform_render_component().

File

components/grid.inc, line 833
Webform module grid component.

Code

function webform_validate_grid($element, $form_state) {
  if ($element['#required']) {
    $values = $form_state['input'];
    foreach ($element['#parents'] as $key) {
      $values = isset($values[$key]) ? $values[$key] : $values;
    }

    // Remove any values that aren't grid question (i.e. nested components).
    $grid_questions = $element['#grid_questions'];
    $values = array_intersect_key($values, $grid_questions);

    // Remove any unanswered grid questions.
    $answers = array_filter($values, function ($item) {
      return !is_null($item);
    });

    // Give required errors for any questions that aren't answered.
    foreach (array_diff_key($grid_questions, $answers) as $question_key => $question) {

      // If the question is still required (e.g not modified by an after_build
      // function), give the required error.
      if (!empty($element[$question_key]['#required'])) {
        form_error($element[$question_key], t('!question field within !name is required.', array(
          '!question' => $question,
          '!name' => $element['#title'],
        )));
      }
    }
  }
}