Skip to content

Instantly share code, notes, and snippets.

@sheanhoxie
Last active April 22, 2021 17:24
Show Gist options
  • Save sheanhoxie/4a5214a7ffb1c86fa60e2c4d2eb22825 to your computer and use it in GitHub Desktop.
Save sheanhoxie/4a5214a7ffb1c86fa60e2c4d2eb22825 to your computer and use it in GitHub Desktop.
Using Drupal's Form Display, we can create variations of a form. This can be helpful in a few ways, including creating simplified forms for different user roles

Creating an entity form variation using Form Display

The UI portion

Create the Form Mode for the entity

  • admin/structure/display-modes/form
  • Note what you name this, as it will be referenced as 'form_mode'

Activate the Form Display

  • admin/structure/{entity_name}/settings/form-display
  • Note the 'form_display' will be the 'entity_name.form_mode'

Edit the Form Display to suite needs

  • admin/structure/{entity_name}/settings/form-display/{form_mode}

The Code portion

Create the new form by extending the entity form you want to override with the new form display

use Drupal\Core\Form\FormStateInterface;

class WeeklyReleaseForm extends SeriesReleaseForm {

public function getFormId() {
  return 'weekly_release';
}

/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  
  // Manipulate form further if you want
  
  return $form;
}

Create the route to the new form which will use the form display (new form will be created in the last step)

module_name.route_name_to_form:
  path: '/whatever/path/here'
  defaults:
    _entity_form: '{form_display}'
    _title: 'Form Title'
  requirements:
    _permission: 'whatever permissions'

Use hook_entity_type_build() to attach the form display to the form

function module_name_entity_type_build(array &$entity_types) {
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['{entity_name}']->setFormClass('{form_mode}', 'Drupal\{module_name}\Form\{FormName}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment