I found this snippet in the code for a form ($roles
is an array of roles).
$form['config_options']['roles'] = [ '#type' => 'checkboxes', '#options' => $roles, ]; // Check and disable the 'authenticated' role. $form['config_options']['roles'][RoleInterface::AUTHENTICATED_ID] = [ '#default_value' => TRUE, '#disabled' => TRUE, ];
What this does is to check the checkbox for the ‘authenticated’ role, and then disables it (so it can’t be unchecked). This works.
I have a very similar requirement. In a form I have checkboxes for a bunch of fields, where $fields
is an array of them. The fields are from user profile. I want to check and disable the ’email’ field.
Based upon the code snippet above, I think the solution should be something like this:
$form['config_fields']['fields'] = [ '#type' => 'checkboxes', '#options' => $fields, ]; // Check and disable the 'email' field. $form['config_fields']['fields'][ -- What to put here? -- ] = [ '#default_value' => TRUE, '#disabled' => TRUE, ];
However, I have no idea what to put in the selector where I’ve written " -- What to put here? --
".
Help will be appreciated.
Also, if I am barking up the wrong tree, and there exists another way to do this, I shall equally appreciate an alternative solution.
(I am using Drupal 9).