Punit
Punit

Reputation: 1120

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;
        }
      }

Upvotes: 1

Views: 1007

Answers (2)

tyler.frankenstein
tyler.frankenstein

Reputation: 2354

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;
  }
}

Upvotes: 2

Piyuesh Kumar
Piyuesh Kumar

Reputation: 436

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!!

Upvotes: 2

Related Questions