Search code examples
drupalhook-form-alter

How to make file attachment required for a content type in Drupal


I want to make the file attachment option as a required field for a specific content type, user could not submit the node form without an attachment.
the way i am doing this is not working, pls guide me if i am doing it wrong way.

function ims_form_alter(&$form, &$form_state, $form_id) {


    switch ($form_id) {

     case 'media_content_node_form':
          unset($form['buttons']['preview']);
          if(is_numeric(trim(arg(3))))
            {
              $arg_nid = arg(3);
              $form['field_media_model']['#default_value'][0]['nid'] = $arg_nid;
            }

            switch($form['#id'])
            {
              case "node-form":
              $form['attachments']['#required'] = true;
              break;
            }

          break;
        }
      }

Solution

  • I find that life in Drupal is easier when using FileField instead of Drupal's core Upload module. With FileField you can create a CCK field (FileField) on your content type and make that field required just like any other CCK field. This approach doesn't require writing a single line of code.

    However, if you must use Drupal's core Upload module then you can use hook_form_alter to accomplish this, for example:

    function my_module_form_alter(&$form, &$form_state, $form_id) {
      switch ($form['#id']) {
        case "node-form":
          switch ($form['type']['#value']) {
            case "my_node_type":
              $form['attachments']['#required'] = true;
              break;
          }
        break;
      }
    }