1

I have a set of custom theme settings defined in my theme.

They are fully integrated into my theme and appear on the theme's setting page but they are not styled. I use the seven admin theme.

I would like to style the forms on the admin pages; similarly to how other core modules like color, logo etc are styled.

How does one go about this?

Ideally, I would group my settings, place them in a div and give the entire group a title and help.

2

Basically it's just these two steps:

  1. Define a library from MYMODULE.libraries.yml.
  2. Attach the library to your form.

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module.

Attaching a library to a form

As forms are just render arrays, attaching a library works just the same:

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  /* @var Drupal\Core\Entity\FieldableEntityInterface $entity */
  $formObject = $form_state->getFormObject();
  if ($formObject instanceof \Drupal\Core\Entity\EntityFormInterface) {
    $entity = $formObject->getEntity();
    if (
      $entity->getEntityTypeId() === 'node'
      && in_array($entity->bundle(), ['organisation', 'location', 'event', 'article'])
    ) {
      $form['#attached']['library'][] = 'yourmodule/yourlibrary';
    }
  }
}

To add additional wrapper divs around some single or multiple form elements you can nest them into containers or fieldsets. For example:

class Container

Provides a render element that wraps child elements in a container.

Surrounds child elements with a and adds attributes such as classes or an HTML ID.

Usage example:

$form['needs_accommodation'] = array(
  '#type' => 'checkbox',
  '#title' => $this
    ->t('Need Special Accommodations?'),
);
$form['accommodation'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => 'accommodation',
  ),
  '#states' => array(
    'invisible' => array(
      'input[name="needs_accommodation"]' => array(
        'checked' => FALSE,
      ),
    ),
  ),
);
$form['accommodation']['diet'] = array(
  '#type' => 'textfield',
  '#title' => $this
    ->t('Dietary Restrictions'),
);

The D7 Form API Reference still is the most useful resource for that. Though you might want to check for changes on the D8 equivalent: Form and render elements.

| improve this answer | |

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.