1

I am wanting to create some fields for a few of my existing content types but not sure how to go about it. Currently I am creating fields like this

function HOOK_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'node') {
    $fields = [];

    $fields['layout_select'] = BaseFieldDefinition::create('list_string')
      ->setLabel(t('Layout selection'))
      ->setName('layout_select')
      ->setSetting('allowed_values', ['one' => 'one', 'two' => 'two'])
      ->setSetting('default_value', NULL)
      ->setDisplayOptions('form', [
        'type' => 'options_select',
        'weight' => 0
      ]);

    return $fields;
  }
}

The problem is, when I set the display options for the form here, they are shown in the main area of the page with the rest of the fields but I want them to be shown in a "details" element in the "#advanced" group on the right side of the edit page like some others are.

Currently, my work around is to define a details element and then just create a form element that corresponds to the field I created with BaseFieldDefinition::create(), like this

function HOOK_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();

  $form['test'] = [
    '#type' => 'details',
    '#title' => t('Test Element'),
    '#group' => 'advanced',
    '#weight' => 99
  ];

  $form['test']['layout_select'] = [
    '#type' => 'select',
    '#title' => 'Layout Selection',
    '#options' => [
      'one' => 'One',
      'two' => 'Two',
    ],
    '#default_value' => $node->layout_select->value ?? NULL
  ];
}

I can't imagine this is the correct way to implement this but I haven't done this before and am not sure how to do it correctly.

1 Answer 1

1

You are doing the correct way to register field and add grouping via form. The grouping is form's scope. You cannot add it from field definition (which is child element of form) One modification, to avoid duplication in your work around(almost there, you are going right)

function HOOK_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
  $form['layout_select']['#group'] = 'advanced';
  $form['layout_select']['#default_value'] = $node->layout_select->value ?? NULL;
}
1
  • Oh good, nice to know I was doing this correctly. Thanks for the advice to avoid duplicating work!
    – Joseph
    Jul 12, 2022 at 18:53

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.