A simple code to disable edition of content types fields.
Last active
April 28, 2021 05:24
-
-
Save pmichelazzo/5160e2094aaadb286593badde038141a to your computer and use it in GitHub Desktop.
Disable field edition by role (Drupal 8)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Primary module hooks for the XXX Content Type module. | |
*/ | |
use Drupal\Core\Form\FormStateInterface; | |
/** | |
* Implements hook_form_BASE_FORM_ID_alter(). | |
*/ | |
function your_content_type_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) { | |
$form_object = $form_state->getFormObject(); | |
// Check the bundle to apply the hook. | |
if ($form_object->getEntity()->bundle() != 'your_bundle') { | |
return; | |
} | |
// If the user has the XXX role(s), disable some fields on the CT. | |
$desired_roles = ['role1', 'role2', etc...]; | |
if (\Drupal::currentUser()->isAuthenticated()) { | |
// Get the roles from the authenticated user. | |
$roles = \Drupal::currentUser()->getRoles(TRUE); | |
if (in_array($desired_roles, $roles) && count($roles) == 1) { | |
// Disable the fields. | |
$form['field_name']['widget']['#attributes']['disabled'] = 'disabled'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment