You are here

function views_send_mail_action_validate in Views Send 6

Validation callback for views_send_mail action configuration form.

See also

http://drupal.org/node/172152

File

./views_send.module, line 228
The Views Send module.

Code

function views_send_mail_action_validate($form, $form_state) {
  $values =& $form_state['values'];

  // Check if sender's e-mail is a valid one.
  if (!valid_email_address(trim($values['views_send_from_mail']))) {
    form_set_error('from_mail', t('The sender\'s e-mail is not a valid e-mail address: %mail', array(
      '%mail' => trim($values['views_send_from_mail']),
    )));
  }

  // Check in the column selected as e-mail contain valid e-mail values.
  if (!empty($values['views_send_to_mail'])) {
    $wrong_addresses = array();

    /**
     * "views_send_mail_action" was the only action configured and "Merge single
     * action's form with node selection view" checkbox is checked. We are on
     * first submit and the $form_state['storage'] is not populated yet.
     */
    if ($values['step'] == VBO_STEP_SINGLE) {

      // Get selection.
      $plugin = $form['#plugin'];
      $form_id = $values['form_id'];
      $form_state['storage']['selection'] = _views_bulk_operations_get_selection($plugin, $form_state, $form_id);
      $records =& $form_state['storage']['selection'];
    }
    else {
      $records =& $form_state['storage']['selection'];
    }

    // When using the action in Rules nothing has been selected.
    if (empty($records)) {
      return;
    }
    $to_mail_field = $values["views_send_to_mail"];
    foreach ($records as $record) {
      $email = _views_send_get_from_views_result($record, $to_mail_field, 'email');
      if (!valid_email_address(trim($email))) {
        $wrong_addresses[] = trim($email);
      }
    }
    if (count($wrong_addresses) > 0) {
      if (count($wrong_addresses) == count($records)) {
        $error_message = t("The field used for recipient's e-mail contains an invalid e-mail address in all selected rows. Maybe choose another field to act as recipient's e-mail?");
      }
      else {
        $error_message = t("The field used for recipient's e-mail contains an invalid e-mail address in @wrong of @total selected rows. Choose another field to act as recipient's e-mail or return to the view and narrow the selection to a subset containing only valid addresses. Bad addresses:", array(
          '@wrong' => count($wrong_addresses),
          '@total' => count($records),
        ));
        $error_message .= '<ul>';
        foreach ($wrong_addresses as $rowid => $wrong_address) {
          $error_message .= sprintf('<li>%s</li>', check_plain($wrong_address));
        }
        $error_message .= '</ul>';
      }
      form_set_error('views_send_to_mail', $error_message);
    }
  }
}