[Resolved] Change the Role of a User thru a Toolset Form

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This thread is resolved. Here is a description of the problem and solution.

Problem: Can we change a user role thru a Toolset Form? If so, how?

Solution: You can, but only using Custom Code. You can see a cred_save_data() hook to fire your custom code when the Form saves the users' data in the database.

Inside that hook, you can use wp_update_user() WordPress API to update the user to any role you desire. For example, you can add a Generic Field to the form where the user can choose his role to which to update, and then you can read it from the $_POST - so to update the user to the desired role with wp_update_user()

Be careful with this as users will be able to eventually change their role. Be sure to grant access to these forms only to whom you trust.

Relevant Documentation: https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data

https://developer.wordpress.org/reference/functions/wp_update_user/

This topic contains 10 replies, has 2 voices.

Last updated by MargeP6083 4 weeks ago.

Assigned support staff: Beda.

Author
Posts
#1465167

I'm trying to find out how to do this:
After a user registers "Pending Industry" role, a notification is emailed to admin with a link to a form that changes the user role from "Pending Industry" to "Industry".

I have set up a form to edit user "Pending Industry". I need for the Admin to see the front end form populated with the user who registered. Submit will change user role to "Industry".

1.How to populate the form with the user data to submit so the Admin can submit?
2. How can I modify code examples below to update the user on the front end form submission?

These api's seem to be of current user, not admin role.
https://toolset.com/forums/topic/change-user-role-after-cred-post-form/
https://toolset.com/forums/topic/change-user-role-with-cred-form/#post-450977

Thank you!

What is the link to your site? hidden link

#1465529

Beda
Supporter

Languages: English (English ) Spanish (Español ) German (Deutsch )

Timezone: Asia/Ho_Chi_Minh (GMT+07:00)

1. How to populate the form with the user data to submit to the Admin can submit?

For example, you can create a View with all those users in the pending role.
Then, in the View Loop, you can insert the Forms (let's say in some accordion or pop up) and that form can take the ID of the use being edited.
You can pass the user ID ShortCode, which will dynamically be populated by the View loop (for each user)

2. How can I modify code examples below to update the user on the front end form submission?

We do not provide ready to use Custom Code, but we can elaborate on the usage of Toolset API.
Code inside the Toolset hooks is custom code, usually, WordPress Codex or PHP Codex can help for this.
If you need help for tailored custom code, we suggest contacting a contractor from https://toolset.com/contractors/

The code elaborated in the 2 tickets does the following:

1. It uses the cred_save_data hook, elaborated here https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
2. Within that hook, it checks if the Form used has ID 279. You will want to adapt this, so it checks if the form with ID as you are using it, is used. That is done in this part of the code:

if ($form_data['id']=='279')

3. Minesh uses the WordPress native function wp_get_current_user() to populate a variable in the code, $current_user, which he later uses to get the ID of that (current) user returned by the WordPress native function wp_get_current_user:

$current_user = wp_get_current_user();
    $user_id = $current_user->ID;

See here the wp_get_current_user doc of WordPress:
https://codex.wordpress.org/Function_Reference/wp_get_current_user
==> This is hence NOT the right approach for you, as you do not want to change the CURRENT use, you want to change the use as edited in that form
The user ID currently EDITED, is *already there*, it is in the Variable $post_id as provided by the Form API hook itself
3a. You can hence use the $post_id to get the ID of the user, and hence, your code becomes much easier.
All you need to do is wp_update_user ( array ( $post_id, 'role' => 'your_desired_role' )); inside the Forms API hook.
wp_update_user is explained closer here https://developer.wordpress.org/reference/functions/wp_update_user/

This is subject to custom code because Toolset does not offer such feature natively:
https://toolset.com/2016/10/create-membership-site-toolset-new-tutorials-available/
>With CRED User Forms it is not possible to change the role.

#1466369

Hi Thanks for your explanations.

1. I created a view with an accordion (not sure if that is correct) like this
https://toolset.com/documentation/user-guides/views/digging-into-view-outputs/#bootstrap-collapse-expand-first-post

The loop is picking up the name, but it is not populating the form with the user form data that needs to be updated. So, I was not able to execute to test part 2.

[wpv-layout-start]
[wpv-items-found]
<!-- wpv-loop-start -->
<div class="accordion" id="accordion2">
    <wpv-loop>
        [wpv-item index=1]
        <div class="accordion-group">
            <div class="accordion-heading">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse-[wpv-post-id]">
					[wpv-user field="user_firstname"] [wpv-user field="user_lastname"] [wpv-user field="user_registered"]
                </a>
            </div>
            <div id="collapse-[wpv-post-id]" class="accordion-body collapse in">
                <div class="accordion-inner">
                   [cred_user_form form='admin-approve-industry-account']  //edits logged in user only
                </div>
            </div>
        </div>
        [wpv-item index=other]  
        <div class="accordion-group">
            <div class="accordion-heading">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse-[wpv-post-id]">
                    [wpv-user field="user_firstname"] [wpv-user field="user_lastname"]
                </a>
            </div>
            <div id="collapse-[wpv-post-id]" class="accordion-body collapse">
                <div class="accordion-inner">
				 [cred_user_form form='admin-approve-industry-account']    //edits logged in user only         
				</div>
            </div>
        </div>       
    </wpv-loop>
</ul>
<!-- wpv-loop-end -->
[/wpv-items-found]
[wpv-no-items-found][wpml-string context="wpv-views"]<strong>No Pending Users Found</strong>[/wpml-string][/wpv-no-items-found]
[wpv-layout-end]

2. I followed what I thought made sense on changing user roles. I added this to the code snippets app in Toolset and ran check.
The error came back A problem occurred when executing snippet "update_industry_role". The result of include_once is: ""
Am I missing something?

add_action('cred_save_data', 'cred_update_user_role_pending',10,2);
function cred_update_user_role_pending($post_id, $form_data) {
if ($form_data['id'] == 4521) {
// update the user role 
  wp_update_user ( array ( $post_id, 'role' => 'Industry' )); 
}
#1466865

Hi I'm still at this and am having lots of issues. I tried the above view. Not good.

I tried these instructions below because I would settle for anything at this point. https://toolset.com/forums/topic/front-end-admin-edit-user-forms/#post-1222902

The pending users are not showing as links to the form. I'm obviously doing this wrong. The instructions are very general. I need the "talking to a 5 year old" version.

thank you!

#1466989

I was able to get this option to work fine: https://toolset.com/forums/topic/front-end-admin-edit-user-forms/#post-1222902

The only thing left is #2 error : The result of include_once is: "" and that code. Can you let me know why this error? And what I need to correct?

Many thanks!

#1470603

Beda
Supporter

Languages: English (English ) Spanish (Español ) German (Deutsch )

Timezone: Asia/Ho_Chi_Minh (GMT+07:00)

You need to tell the Form what user to edit.
When you insert the Form, it asks what user to edit.
There, insert any number.

Then insert the ShortCode and change the user to [wpv-user-id], which will then pick up the ID of the User in the Loop.

That will guarantee that you are getting that data into the form.
Like so:

[cred_user_form form='edit-user' user='[wpv-user field="ID"]']

I'm not sure on the second error you report (The error came back A problem occurred when executing snippet "update_industry_role". The result of include_once is: "")
I am not using include() in that code I suggested you, the error cannot be related and likely is due to something else.
I suggest opening a new ticket if you keep receiving that error, as it seems related to generic errors when saving code?

Your form does not yet work, it can't, if you did not pass the user ID, as shown above, hence even applying what's mentioned in https://toolset.com/forums/topic/front-end-admin-edit-user-forms/#post-1222902, which is only related to whether a user is an admin or not, the form still would not work
This part is required if you are not an admin on the site if the form should be public, or for lower roles

1. Please ensure your form works in the View and you can edit Users successfully
2. Once that is done, please remove anything from the Form that you do not want to be edited
3. Then, apply any Access rule, that you may need if these forms should be used by lower than admin users.
4. Test the form in the view again, as one of those lower-than-admin users
5. Now add the Custom code either to your theme's functions.php or the custom code section.
Enable WP Debug and run the form again to see if there are any errors.
WP debug can be enabled like so: https://codex.wordpress.org/WP_DEBUG

At this point, if there are errors, it will log them to the error log and we can take from there (eventually we will need to include the user.php file once, in the Code)
If that is needed, you can add before all else this line:

require_once(ABSPATH.'wp-admin/includes/user.php');

So the Snippet becomes

add_action('cred_save_data', 'cred_update_user_role_pending',10,2);

function cred_update_user_role_pending($post_id, $form_data) {
require_once(ABSPATH.'wp-admin/includes/user.php');

if ($form_data['id'] == 4521) {
// update the user role 
  wp_update_user ( array ( $post_id, 'role' => 'Industry' )); 
}

If you need deeper help with custom code, I would suggest contacting a contractor https://toolset.com/contractors/.

Please let me know if with above you could achieve your goal. I can try to help and pinpoint to further details if needed.

#1471685

Hi thanks for the message. The form is appearing fine with content template, no need for the shortcode. I'm able to update/change the user info in the fields, but clicking submit does not change the user role.

The code was missing a curly bracket, so that was the error. It's just not updating the user role.

Thanks!

#1472015

Just for comparison, I tested the other way (radio) and that did work.

[cred_generic_field type='radio' field='approve-deny-pending-user']
{
	"required":1,
"default":[],
"options":[{"value":"pending_industry","label":"Pending Approval"},{"value":"industry","label":"Approve Industry"},{"value":"subscriber","label":"Reject Approval"}]
}
[/cred_generic_field] 
add_action('cred_save_data', 'cred_update_user_role_action',10,2);
function cred_update_user_role_action($user_id, $form_data) {
     
   if ($form_data['id'] == 4521)
  {
  // modify the user role to match the selected option
    $role = $_REQUEST['approve-deny-pending-user'];
    $u = new WP_User( $user_id );
    $u->remove_role( 'pending_industry' ); //cred form role setting
    $u->set_role( $role );
  }
}
#1472241

I think the last code is a good choice for me. One last question about that...

Will the format be different for a custom field?

I removed the generic field, cleared cache and added a custom field with the same slug. I thought custom user field may work better for notification triggers/notification emails.

Thanks!

#1472537

Beda
Supporter

Languages: English (English ) Spanish (Español ) German (Deutsch )

Timezone: Asia/Ho_Chi_Minh (GMT+07:00)

What do you mean that you do not need the ShortCode?
Without it - no form will display. Maybe I misunderstand?

I see now you are able to update/change the user info in the fields, but clicking submit does not change the user role, meaning everything but the custom code works.
I see you even brought the custom code to work using a Radio field instead of... I am not sure what you used instead.

I provided the code sample with hardcoded value.
If you need to grab this value from a Generic Field, you need to get the value from the $_POST object as PHP native post methods want us to:
hidden link

So in your code you can, for example, get $_POST['html-name-of-field']

That format is depending on what you see in the HTML in the Form.
So it's recommended to open the browser console and look out for the HTML input you want to get data from, then copy-paste it's identifiers to the code.

This will work whether it is a custom field, a title, or else, as it is in the $_POST - so depending on what the form POSTs.

Please let me know if you need further help with this.

#1475839

get $_Post worked great for the custom field. Thanks for all the help!

My issue is resolved now. Thank you!