At some point, you might want to restrict sections of a form to certain users and roles. That can be accomplished relatively easy by creating a module that implements 2 Drupal hooks: hook_form_alter and hook_perm.
First, I start by adding the hook_perm():
<?php
function MYMODULE_perm() {
// return an array of permissions,
// they can be named whatever you'd like.
// NOTE: avoid redeclaring permissions that are already set
return array('access secret section of my form');
}
?>Next, add a form_alter hook:
<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
// test for the form id you'd like to alter.
// if you are unsure of the it's exact name,
// you could add this: echo $form_id . "<BR>";
if ($form_id =='SOME_FORM_ID') {
// check if the user has access to the permission you defined
if (!user_access('access secret section of my form')) {
// deny access to the form element
// if you don't what what it's called,
// output the $form object:
// echo "<pre>" . print_r($form, true) . "</pre>";
$form['SOME_FORM_ELEMENT']['#access'] = false;
}
}
}
?>Now, if you enable you module you can restrict permissions by going here: /admin/user/permissions





















Comments
Hey Eric, would this allow me
Hey Eric, would this allow me to restrict the contact form on users profiles? If so, I've been trying to do this forever!
here's a tip
The above code allows you to restrict access to sections of a form. For instance, if you wanted to change permissions on the title or body of the user contact form.
If you are looking to change permissions of who can access a page (the user contact form is a page callback), you should check out hook_menu_alter.
I created a quick snippet to show me the menu item for the user contact form.
<?php
function MYMODULE_menu_alter(&$items)
{
// NOTE: if you are unsure of which item it is,
// you can dump the entire contents of the $items array
echo "<pre>";
print_r($items['user/%user/contact']);
echo "</pre>";
}
?>
The output shows an associative array. Check out the "access" keys:
[access callback] => _contact_user_tab_access[access arguments] => Array
(
[0] => 1
)
The above shows you which function handles access to that menu item (_contact_user_tab_access) and which arguments are passed to it. If the current permissions defined by a module will not work for you, you could modify the menu item for the page callback. For instance, you could insert your own access callback function, replacing "_contact_user_tab_access".
<?php$items['user/%user/contact']['access callback'] = 'MYMODULE_MY_ACCESS_FUNCTION'
?>
I created a blog entry that used the menu_alter hook, which may help.
Thanks, I will give this a
Thanks, I will give this a try!
-Ryan