Simple permissions for uploads per node type

19th Aug

Simple bit of Drupal module code from yesterday: permissions are provided for each node type which can have attachments, providing a more granular permission set based on node type. Then, we alter any node add/edit forms and set the #access property for the attachments part of the form based on these new permissions.

Check the code out after the break, hope its of some use somewhere. Does anyone have any thoughts on unsetting form elements like this? Is it a wise thing to do, or is there a better way? Cheers to those who commented, I've modified the snippet accordingly.

  1. /* @file attachments_by_nodetype.module
  2.  *
  3.  * Simple granular permissions for uploading files per node type.
  4.  */
  6. /* Implementation of hook_perm(). */
  7. function attachments_by_nodetype_perm() {
  8. $permissions = array();
  10. foreach (node_get_types() as $type => $type_name) {
  11. if (variable_get("upload_$type", 0) == 1) {
  12. $permissions[] = "upload files to $type nodes";
  13. }
  14. }
  16. return $permissions;
  17. }
  19. /* Implementation of hook_form_alter(). */
  20. function attachments_by_nodetype_form_alter($form_id, &$form) {
  21. if ($form['type']['#value'] .'_node_form' == $form_id) {
  22. $form['attachments']['#access'] = user_access("upload files to {$form['type']['#value']} nodes");
  23. }
  24. }


$element['#access'] = FALSE

$element['#access'] = FALSE

Cheers Mr Anonymous

Ta for that! However, it looks to me from the Form API notes that this attribute was added in Drupal 6?

Unfortunately, the site the code is used on is based on Drupal 5.

In Drupal 5

It's available in Drupal 5 but for some reason isn't in the documentation.

Actually... it's just undocumented.

If you check out the node_form() function (at ) in d5 you'll find:

 // Node options for administrators
  $form['options'] = array(
    '#type' => 'fieldset',
    '#access' => user_access('administer nodes'),
    '#title' => t('Publishing options'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#weight' => 25,

However the FAPI documentation does not cover it. Patch time?!

Edit: yes indeedy! Paul

User 1 should always be allowed to do anything...


'#access' => FALSE

should maybe be something like

'#access' => user_access('user 1 only')

where 'user 1 only' could be any old string, since the function always returns true for U1...