Score:1

Set entity field to read-only after user input

ru flag

I am using hook_entity_presave() to check some conditions and set field value. I would like to set the field to read-only after all conditions pass and the value is saved to database. Is it possible to achieve this or must I use another hook for this?

cn flag
Read-only for the user who set the value? For all users? For the admin? To implement something like read-only, you could use `hook_form_alter()` on the edit form to unset the field if it already has a value.
Bass-Ninja avatar
ru flag
@PatrickKenny sorry for being unclear. Only for the user who set the field. I want to avoid them changing the value after they set it.
cn flag
Can each user only edit the user's own content? Or can multiple users edit the same piece of content? (If multiple users can edit the same piece of content, then it's also necessary to keep track of who editing a specific field, which is something Drupal doesn't do out of the box.)
Bass-Ninja avatar
ru flag
The current user is the only one editing the content. Also, I was able to achieve the desired effect with hook_form_alter(). Thank you.
cn flag
Great, please post your code (or a similar example) as an answer for future visitors to the site.
Score:0
ru flag

I was able to achieve my result by using the following hook:

function check_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == "form_id") {
    $form['field_example']["#disabled"] = TRUE;
  }
}
Score:0
kr flag

Disable Field module is what you're looking for.

Disable Field module help(s) you to disable the field of any content type ... based on Role selected By Admin.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.