Apologies for the re-submission. I'm re-submitting with sample code, since I can't delete my previous request (forum throws an error).
Can you tweak this code so it works? Here's what it needs to do..
This needs to create/update users and assign multiple user roles from a checkbox field. It does not. It creates/updates a user with the role set in the form action, ignoring the values in the checkbox field. They're custom roles and they're set up correctly in the form with separate values.
form key: custom-roles field key: 'custom_user_roles' valid roles: 'custom_role_one', 'custom_role_two', 'custom_role_three', 'custom_role_four'
-- CODE SNIPPET --
function assign_user_multiple_roles($entry_id, $form_id) {
// Check if the form ID matches the target form
$target_form_id = FrmForm::get_id_by_key("custom-roles");
if ($form_id == $target_form_id) {
// Get the user ID from the form submission
$user_id = isset($_POST['frm_user_id']) ? (int)$_POST['frm_user_id'] : 0;
// Make sure the user ID is valid
if ($user_id > 0) {
// Get the user object
$user = get_userdata($user_id);
// Check if the user object exists
if ($user instanceof WP_User) {
// Get the selected roles from the form submission
$selected_roles = isset($_POST['custom_user_roles']) ? (array)$_POST['custom_user_roles'] : [];
// Define an array of all valid roles
$all_valid_roles = ['custom_role_one', 'custom_role_two', 'custom_role_three', 'custom_role_four'];
// Clear existing roles
foreach ($user->roles as $role) {
$user->remove_role($role);
}
// Loop through the selected roles and add them
foreach ($selected_roles as $role) {
if (in_array($role, $all_valid_roles)) {
$user->add_role($role);
}
}
}
}
}
}
// Hook into Formidable Forms after entry creation and update
add_action('frm_after_create_entry', 'assign_user_multiple_roles', 30, 2);
add_action('frm_after_update_entry', 'assign_user_multiple_roles', 30, 2);
The register user action has a default role. It can be changed, but it can't be blank.
My question still stands though. Do you know if your code is being executed and, if so, is the end result what you're hoping for and it's overridden later? I suggest debugging either with a debugger or some error_log statements after you turn debugging on.
Used query monitor and there's no errors. If I add a default value into the function, that's what gets saved.
Having no errors doesn't mean it's doing the right thing, though I guess the default value is proof that something's happening. I still suggest turning on debugging and using error_log to find out what's going on at each line.
https://wpforms.com/developers/how-to-enable-debugging-in-wordpress/
Will do this again. Caught a false positive thrown by a security plugin, but maybe dumping server cache and removing the default value from the function will yield some clues. Thanks, Rob.
Please login or Register to submit your answer
Sorry for the formatting. This forum's post editor is kinda wacky. 🙂