1

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;
        }
      }
Punit
  • 1,110
  • 1
  • 8
  • 14

2 Answers2

2

Yes it is possible.

  1. Check for the form id. Usually you can get the name by inspecting the form and getting the id. Replace '-' by '_'. This gives you the form id for the form.
  2. Put a conditional check if form id == . Use krumo($form) (enable devel module before this step).
  3. krumo() give you the list of all the field names. Now, $form[<field_name>]['#required'] = 1;

Hope this helps!!

Laxman13
  • 5,226
  • 3
  • 23
  • 27
Piyuesh Kumar
  • 436
  • 5
  • 21
  • appreciated, but if i am using default file attachment method which has ajax uploading so how do i know exact field name. – Punit Sep 22 '11 at 06:48
2

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;
  }
}
tyler.frankenstein
  • 2,314
  • 1
  • 23
  • 36
  • this is looks like a default settings for attachments, but i am only want to make it for a specific content type in my case it's "media-content", for more i am changing my question to show how i am doing this. – Punit Sep 22 '11 at 04:54
  • I have updated the code with a switch/case so you can limit these form alterations to a specific node content type. – tyler.frankenstein Sep 22 '11 at 13:23