1

I have some radio buttons such as draft, need review, etc. I want to remove (omit) the required fields when draft is selected, and click on the submission button. I tried with below code but it is not working.

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
 if($form_id =='catalog_node_form')
 {
  $form['#validate'][] ='remove_required_field';
 } 
} 

function remove_required_field($element)
{ 
 foreach (element_children($element) as $name) 
 { 
  $element[$name]['#required'] = FALSE; 
 } 
 return $element; 
}
3

2 Answers 2

1

In the form_alter function you can use the limit_validation_errors property.

'#limit_validation_errors' => array(),

The above code will not perform any field validations. You can then add the individual fields that you need to validate here using the below code.

$form['actions']['next']['#limit_validation_errors'][] = array($field_key);

Where next is the action that I am using.

3
  • 1
    Good way, but possibly a bit overcomplicated.
    – Mołot
    Commented Feb 11, 2014 at 10:36
  • True. It may be a little over-complicated. I wanted the control as I was building a multi-step registration form and hence it made sense in my case :)
    – Gokul N K
    Commented Feb 11, 2014 at 11:02
  • Yea, if you want to leave evaluation to the original module, your way is better than mine. But if original module only sets #required, my way is simpler. So, it all depends on use-case.
    – Mołot
    Commented Feb 11, 2014 at 11:55
1

Problem with your code is caused by the fact that #required is resolved before custom validation handlers. Thus, when remove_required_field() is called, it's already too late.

Instead, un your mymodule_form_alter() hook set:

$element[$name]['#required'] = FALSE; 
$form['#validate'][] ='function_that_will_test_checkbox_only_if_its_needed';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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