2

I've created a field programmatically :

$field_storage = FieldStorageConfig::create(
  array('entity_type' => 'node', 'field_name' => 'field_desc', 'type' => 'string'));
$field_storage->save();
$field = FieldConfig::create(
  array('entity_type' => 'node', 'field_name' => 'field_desc', 'bundle' => 'mybundle', 'settings' => array('handler' => 'default', 'handler_settings' => array())));
$field->save();

But the field is disabled by default when I access to "manage form display".

My question is : how can I enable the field programatically?

thanks :)

1 Answer 1

4

You enable the field by adding a widget to the default form display mode:

$display_repository = \Drupal::service('entity_display.repository');

// Assign widget settings for the default form mode.
$display_repository->getFormDisplay('node', 'mybundle')
  ->setComponent('field_desc', [
    'type' => 'string_textfield',
  ])
  ->save();

See Add content type field programmatically

1
  • Another hint for things like this is to look at the core kernel and functional tests. You can learn a lot from the setUp() methods.
    – mpdonadio
    Oct 24, 2020 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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