1

I have a form where a user picks a date for their submission(s) to appear on the website. I am populating a 'date' field like so:

function mymodule_get_date_options($type = 'start') {
  $options = array();

  $start_week = time();

  if (date('w', $start_week) == 3) {
    $start_week = strtotime('+1 week', $start_week);
  }

  while (date('w', $start_week) != 3) {
    $start_week = strtotime('+1 day', $start_week);
  }

  if ($type == 'end') {
    $start_week = strtotime('+1 week', $start_week);
  }

  for ($x = 0; $x < 24; $x++) {
    $options[date('U', $start_week)] = date('M d, Y', $start_week);
    $start_week = strtotime('+1 week', $start_week);
  }

  return $options;
}

And the element:

$form['start_date'] = array(
    '#title' => t('Start Date'),
    '#type' => 'select',
    '#options' => mymodule_get_date_options('start'),
    '#default_value' => $mymodule_form_object->start_date,
  );

The generated HTML:

// a chunk of the option elements
<option value="1313615248">Aug 17, 2011</option>
<option value="1314220048">Aug 24, 2011</option>
<option value="1314824848">Aug 31, 2011</option>
<option value="1315429648">Sep 07, 2011</option>
<option value="1316034448">Sep 14, 2011</option>
<option value="1316639248">Sep 21, 2011</option>
<option value="1317244048">Sep 28, 2011</option>
<option value="1317848848">Oct 05, 2011</option>
<option value="1318453648">Oct 12, 2011</option>

So, everything looks okay, except when the form is submitted it says 'An Illegal Choice has been detected" with the date selects highlighted.

6

That's because the form gets generated both upon output and submission, and you're using form values that are time-dependent. When you first output the form it generates options like this:

1313615248
1314220048
1314824848
1315429648

And when a user submits the form, it will generate new values, with a few second difference:

1313615268
1314220068
1314824868
1315429668
(+20 second difference)

So none of the previous options are present here. Drupal's validator by default checks if the submitted option is among generated options.

  • Of course. Can't believe that didn't dawn on me. Thanks. – Kevin Aug 10 '11 at 12:40
  • $start_week = strtotime('midnight'); solved. Thanks! – Kevin Aug 10 '11 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.