سؤال

I have a form that has a bunch of CCK fields, one of which is a master "request type" field.

The other fields on the form are required depending on the state of the master field.

Example form:


{master field}

{field one} (required always, set by cck form)

{fieldgroup my group for vertical tabs} {

-{field two} (required IF master field == '1')

-{field three} (required IF master field == '1' OR '2')

}


I have been trying to accomplish this using the form validation, at this stage Im trying to make the field required on the fly without even checking the masterfield but I cant make it render as a required field on the form...

function my_module_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) 
  {
   case 'my_node_node_form':
    $form['#validate'][] = 'my_module_form_validate';
    break;
   default:
    // nothing
    break;
  }
 }

function my_module_form_validate($form, &$form_state) {
  // there are so many versions of the same field, which one do I use?
  $form['#field_info']['field_two']['required'] = '1'; 
  $form['group_my_group']['field_two']['#required'] = '1';
  $form['group_my_group']['field_two'][0]['#required'] = 'TRUE';
 }

When I submit the form all I get is Field One field is required.

When I do a print_r dump on the $form in the validation function, it shows that I am successfully changing the values but its not rendering as required.

How do I make a field required depending on another fields value?

هل كانت مفيدة؟

المحلول

I figured out the key was not to use $form['#validate'][] but $form['#after_build'][], like this

function my_module_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) 
  {
   case 'my_node_node_form':
    $form['#after_build'][] = 'my_module_form_after_build';
    break;
   default:
    // nothing
    break;
  }
 }

function my_module_form_after_build($form, &$form_state) {
  switch ($form['field_master_field']['#value']['value']) {
    case '2':
      $form['group_my_group']['field_three'][0]['value']['#required'] = TRUE;
    case '1':
      $form['group_my_group']['field_two'][0]['value']['#required'] = TRUE;
    case '0':
      $form['group_my_group']['field_one'][0]['value']['#required'] = TRUE;        
     break;
    }
   return $form;
  }

Works a treat

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top