Thanks for the update and glad that the code is working now.
> 1. To keep the default user role (contributor) while allowing other roles to be added and/or removed. Even though I didn't include contributor in the form, it still removes default user role and adds the default user role option to the first selected role.
- If you'd like the 'contributor' role to always be added by the form, as the primary one, regardless of the selected options, you can update the code snippet from my last reply to:
add_action('cred_save_data', 'change_user_roles', 10, 2);
function change_user_roles($post_id, $form_data) {
if ($form_data['id'] == '137') { // Replace 'form_ID' with the ID of your form
// get field value from 'select-user-roles'
$user_field_val = types_render_usermeta( "select-user-roles", array( "separator" => "," , "user_id" => $post_id ) );
// check if some field value exists
if(!empty($user_field_val)) {
// get user's info
$user = new WP_User($post_id);
// set default user role 'contributor'
$user->set_role('contributor');
// create an array of the field value from 'select-user-roles'
$user_field_val_arr = explode(',', $user_field_val);
// loop through the selected roles to add them as additional roles
for ($i=0; $i < sizeof($user_field_val_arr) ; $i++) {
$user->add_role($user_field_val_arr[$i]);
}
}
}
}
> 2. Your suggestion under the 'Important note' in your previous response.
- You can use the filter 'cred_form_validate' for this purpose too:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate
For example:
add_filter('cred_form_validate','change_user_roles_validation',10,2);
function change_user_roles_validation($error_fields, $form_data)
{
//field data are field values and errors
list($fields,$errors)=$error_fields;
//validate if specific form
if ($form_data['id']==137)
{
// if no option is selected for the 'select-user-roles' field
if( empty($fields['wpcf-select-user-roles']['value']) ) {
$errors['wpcf-select-user-roles'] = 'At least one role needs to be selected!';
}
}
//return result
return array($fields,$errors);
}
The above code will check the form submission and if none of the options from the 'select-user-roles' field are selected, it will show the error message.
For your third question, I've created a separate ticket and will follow up on that shortly.
( ref: https://toolset.com/forums/topic/split-how-to-restrict-access-to-the-form-for-specific-user-roles/ )