The Community forums are being phased out in favor of a new Slack group.
Add your email address below to get an invitation to join the community slack group

Slack Signup
Newsletter Optin
Help Desk

Code for granular form permissions

Labels

This Discussion is public

Notifications

Hello,

I share this custom code to enable granular form permissions. When a user attempts to edit a form from wp-admin, this checks if the user has the capability "manage_form_XX" where "XX" is the ID of a Formidable form. If the user has the cap for the form they are attempting to access, they will be able to do so as normal. If the user is trying to access a form without the correct capability, they will get a permission denied error.

Any suggestions or improvements on this snippet would be more than welcome! I'm sure there's a few power users who have a use-case for form-by-form access control, so hopefully someone finds this code useful.

function go_form_access( $all_caps, $cap, $args ) {
 $cap = reset( $cap );
 global $pagenow;
 
 if ( strpos( $cap, 'frm_' ) !== 0 )
 return $all_caps;
 
 // save initial values
 $view_forms = isset( $all_caps['frm_view_forms'] ) ? $all_caps['frm_view_forms'] : 0;
 $edit_forms = isset( $all_caps['frm_edit_forms'] ) ? $all_caps['frm_edit_forms'] : 0;
 
 // add these so that the menus and links show up
 $all_caps['frm_view_forms'] = 1;
 $all_caps['frm_edit_forms'] = 1;
 
 //get URL variables
 if ( ( $pagenow == 'admin.php' ) && ($_GET['page'] == 'formidable-entries') || ( $pagenow == 'admin-ajax.php' ) && ($_GET['action'] == 'frm_entries_csv') ) { //check if we are attempting to view entries or download the entries csv
 $form_id = isset( $_GET['form'] ) ? $_GET['form'] : null; // we are so get the 'form' variable
 }
 else {
 $form_id = isset( $_GET['id'] ) ? $_GET['id'] : null; //we aren't (e.g. if we are editing the form) so get the 'id' variable
 }
 
 // see if the capability exists for this form for this user
 $per_form_cap = 'manage_form_' . $form_id;
 
 if ( $form_id && isset( $all_caps[ $per_form_cap ] ) && 1 == $all_caps[ $per_form_cap ] ) {
 // enable all caps when viewing authorized form
 $all_caps['frm_edit_forms'] = 1;
 $all_caps['frm_view_entries'] = 1;
 $all_caps['frm_edit_entries'] = 1;
 $all_caps['frm_create_entries'] = 1;
 $all_caps['frm_delete_entries'] = 1;
 $all_caps['frm_view_reports'] = 1;
 } elseif ( $form_id ) {
 // return caps to defaults when on potentially unauthorized form
 $all_caps['frm_view_forms'] = $view_forms;
 $all_caps['frm_edit_forms'] = $edit_forms;
 }
 
 return $all_caps;
}

add_filter( 'user_has_cap', 'go_form_access', 10, 3 );

 

Thanks for sharing, this will be useful I am sure.

Discussion closed.