0

I have a field that should not be visible when editing, in certain cases (depending on node state and user). It works fine using hook_field_access():

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ( ...conditions on $entity_type, $entity->type, $field['field_name'], $op...) {
    // → $op=='edit' && isset($entity->nid) so only when modifying existing content
    return FALSE;
  }
  return TRUE;
}

As said it works fine, and the field is not displayed at all when access is not granted.

But in some particular conditions I would like to let the field visible but readonly (grey-ed, or anything preventing to modify it) rather than hiding it.

I tried to return TRUE and before to set according attributes to the field, but until now I failed to make it works as expected. What I tested:

$tmp = mode_load($entity->nid);
$tmp->my_field['#attributes'] = array('readonly' => 'readonly'); // also tried to use 'disabled')
node_save($tmp);

I also tried:

$tmp->my_field['#disabled'] = true;

Thanks for any help.

Regards.

  • You need to alter this field at display or on edit form ? – florian_drupal Oct 13 '17 at 10:53
  • On edit. My conditions to hide the field is for preventing some users in some conditions to edit this field. But in some other cases I would like them to be able to see the field value when editing, but not to modify it. – hexasoft Oct 13 '17 at 11:01
1

Try something like that :

Replace FORM_ID with the real form ID.

function MYMODULE_form_FORM_ID_alter(&$form, &$form_state) {

  if(!user_access(ADMIN_USER)){
      $form['your_field_name']['#disabled'] = TRUE;
    }

    $form['your_field_name']['#access'] = TRUE;
}
  • Thank you. This example does (part of) the trick. But in my particular case I allow the field with more complex criteria. For example the field is writable at creation (($op=='edit') && isset($entity->nid) to restrict only on existing content). Is it possible from form-alter to get similar informations than from field_access? – hexasoft Oct 13 '17 at 13:03
  • Hmm… Yes I can: $node = $form_state['node']; if (!isset($node->nid) or isset($node->is_new)) { ...this is a node creation... }. – hexasoft Oct 13 '17 at 13:58
  • Maybe you can clarify for me: is it whatever possible to alter a field from field_access()? – hexasoft Oct 13 '17 at 14:09
  • If you want to alter the form on node/add/article use : function MYMODULE_node_article_form_alter(&$form, &$form_state) and if you want to alter the form on node/{id}/edit use : function MYMODULE_node_article_edit_form_alter(&$form, &$form_state) – florian_drupal Oct 13 '17 at 15:39
  • field_access can't alter your field, return TRUE if the operation is allowed, and FALSE if the operation is denied. – florian_drupal Oct 13 '17 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.