4

I am trying to theme Contact form with template file, manipulating the contact form with form API, trying to hide the subject field and make it optional for submission.

$form['subject']['#required'] = FALSE;
hide($form['subject']);

I used dsm() to confirm that the #required is successfully set to FALSE.

screenshot

However, when I submit the form, it still ask me to fill in Subject field. (The cache has been cleared.)

enter image description here

These are the steps that I have followed:

  • In the template.php file I added the following code

    function mytheme_theme() {
      return array(
        'contact_site_form' => array(
          'render element' => 'form',
          'path' => drupal_get_path('theme', 'mytheme') . '/templates',
          'template' => 'contact-site-form',
        ),
     );
    
  • I created the contact-site-form.tpl.php file with the following code

    $form['subject']['#required'] = FALSE;
    hide($form['subject']);
    print drupal_render_children($form);
    
  • I cleared the cache

0

4 Answers 4

6

Yes, theming the form only changes its markup. If you want to change the form you have to hook_form_alter.

I once wondered how to add required styles to elements that weren't actually required. Your question just gave me the answer.

1
  • ... and in your hook_form_alter function, don't forget to pass $form as reference (e.g hook_form_alter(&$form)) {}
    – AKS
    Dec 20, 2012 at 16:26
4

I see that its an old post but still... try to use this via hook_alter()

$form['subject'][und]['#required'] = FALSE;

well worked in my case:

$form['field_client']['und']['#required'] = FALSE;
hide($form['field_client']);

interesting that for 'title' field its just:

$form['title']['#required'] = FALSE; 
2

I don't know why your form field is still failing on validation, but try $form['subject']['#access'] = FALSE; to achieve what you want.

7
  • $form['subject']['#access'] = FALSE; doesn't work. "Subject field is required" still.
    – gilzero
    Dec 8, 2011 at 11:44
  • Hmm, what version of Drupal? If you give me the whole hook I can try/play with it on a test system.
    – Malks
    Dec 8, 2011 at 12:04
  • Drupal 7. Then enable the contact form. Go to /contact. See if you can make the subject field optional with FORM API?
    – gilzero
    Dec 8, 2011 at 12:20
  • I have updated the questions, upload the screenshot of code and the steps. Thanks in advanced.
    – gilzero
    Dec 8, 2011 at 12:40
  • 1
    I got it. I Should use hook_form_alter. Thanks anyway.
    – gilzero
    Dec 8, 2011 at 14:18
2

In drupal 8

$form['field_first_name']['#access'] = FALSE; $form['field_last_name']['#access'] = FALSE; $form['field_gender']['#access'] = FALSE;

works fine for me.

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.