I am new to Drupal so forgive my newb question.

I am trying to remove the required true from a form field if a user clicks on a certain button so i tried to do it via form validaiton:

$form['#validate'][] = 'my_from_after_build'; //Calls function

function canvas_from_after_build($form, &$form_state) {
  echo "this is the form after building";
  $form['field_title_tag_list_article']['widget'][0]['#required'] = FALSE;
  return $form;

but it still gives a "this field is required" error.

  • Welcome to Drupal Answers :) If your requirements allow for it, it might be easier to set required to false by default, and check the opposite condition in the validate handler. Otherwise you're fighting against the existing validation methods. You might get away with inserting your validate function at the start of the $form['#validate'] array, passing the $form in by reference to the validate function, and altering it there. But even if it does work it's a bit of a hack
    – Clive
    Commented Aug 29, 2018 at 22:11
  • Have you looked into using #states? Check out lullabot.com/articles/form-api-states
    – Beau
    Commented Aug 29, 2018 at 23:38

1 Answer 1


The validation function in the Form API is meant to evaluate the user input and report the errors back to the user if any.

You could change your logic in this way to facilitate your implementation: - The field _field_title_tag_list_article_ is not required by default - In the validation function, you would check whether the value of a second field (i.e. _field_validate_titles_) is set to a given value (i.e. _field_validate_titles_ == 'needs validation').

It would look something like this:

if ($form_state['values']['field_validate_titles'] == 'needs validation' &&
  empty($form_state['values']['field_title_tag_list_article'])) {
  form_set_error('field_title_tag_list_article', t('The title tags are required.'));

You could download the Drupal Examples modules and install the _form_example_ module, then check the example number 6.

Advice for new users

In general, I suggest you browse the examples so that you are familiar with this handy reference.

Quite often, you will find that someone else had the same problem before. Sometimes, there is a community contributed module that solves your problem.

In your particular case, the conditional fields module could help you accomplish your goal without having to write a single line of code:

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.