Basically it's just these two steps:
- Define a library from
MYMODULE.libraries.yml
.
- 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.