0
votes

I am trying to do something that should be extremely easy in drupal. I just want to simply hide a form field in the drupal admin by default.

Making the field disabled simply doesn't work. I cannot find any documentation for this. It's unbelievable that it's this hard to do something so simple in Drupal.

$form['field_name']['#states'] = [
  'visible' => [
    ':input[name="field_foo[0][target_id]"]' => ['value' => 'blah'],
  ],
  'invisible' => true,
];

The visible part works. If another field has a certain value, then show the form element.

But I simply cannot get it to hide this field on default when you're adding a new node.

4
not quite sure about your question but will conditional fields module help? You could also use some js with a custom module and form alter. Then is quite easy to do whatever you need with your form/node. - Florin Simion

4 Answers

1
votes

Add into form element array $element = ['#access' => FALSE,]:

$form['field_name'] = [ 
  '#access' => FALSE,
]
0
votes

You don't need to set invisible, it will be hidden by default unless the visible condition is met. Also the input looks to be wrong, as it should be whatever the name attribute is set to in the element you are basing the condition on.

The drupal.org documentation with an example.

e.g.

$form['field_name']['#states'] = [
  'visible' => [
    ':input[name="field_conditional_on"]' => ['value' => 'value_conditional_on'],
  ],
];
0
votes

Or if you just want to hide it using CSS's display property, you could use something like below,

$form['field_name']['#states'] = [
  '#attributes' => array('style' => array('display: none;')),
 ];
0
votes

Easy and does not affect your default value (if default is set):

$form['field_name']['#attributes']['class'][] = 'hidden';

Drupal core will "display: none;" this element from core styles using the 'hidden' css class.