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? --
".
Based upon a comment from Clive I've tried to examine $fields
. This is what the devel Default variables-dumper gives me (using short array syntax):
$fields = [
â¦
mail => stdClass Object (
[__CLASS__] => Drupal\Core\StringTranslation\TranslatableMarkup
[translatedMarkup:protected] =>
[options:protected] => []
[stringTranslation:protected] =>
[string:protected] => Email
[arguments:protected] => []
)
â¦
]
So it is a bit more complex than the example given in Clive's comment (e.g. it is an object, not an array (as implied by Clive).
So far I've tried 'Email'.
$form['config_fields']['fields'] = [
'#type' => 'checkboxes',
'#options' => $fields,
];
// Check and disable the 'email' field.
$form['config_fields']['fields']['Email'] = [
'#default_value' => TRUE,
'#disabled' => TRUE,
];
This does not work.
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).