Search code examples
formsvalidationdrupaldrupal-6

Drupal 6 - ignore required form field


I need to ignore the validation of two form field while creating a user in Drupal 6 but I don't know at all how to do :

  $userinfo = array(
    'name' => $login,
    'init' => $mail,
    'mail' => $mail,
    'pass' => $password,
    'status' => 1,
    'lastname' => "", //how to ignore those required fields that invalidate the form
    'surname' => ""   //how to ignore those required fields that invalidate the form
  );

  // register a new user
  $form_state = array();
  $form_state['values'] = $userinfo;
  drupal_execute('user_register', $form_state);
  $errors = form_get_errors(); // getting 2 required field errors

Note that I can't supress the "required" property as it is used elsewhere in a more "complex" form.

Thanks


Solution

  • I haven't got a D6 site handy to test this on but I think it'll work...

    Since drupal_execute() pushes you through the whole form build process you can take advantage of hook_form_alter() to remove the required status, but only in a context you pass along in the $form_state. For example

    function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
      if ($form_id == 'user_register' && !empty($form_state['custom_execution'])) {
        $form['lastname']['#required'] = FALSE;
        // etc...
      }
    }
    
    ...
    
    $form_state = array();
    $form_state['values'] = $userinfo;
    $form_state['custom_execution'] = TRUE;
    drupal_execute('user_register', $form_state);