Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sheanhoxie/094690c5b63be7acb81ed081b65c594c to your computer and use it in GitHub Desktop.
Save sheanhoxie/094690c5b63be7acb81ed081b65c594c 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 creating simplified forms for different user roles
h1. Creating a variation of an entity form
1. [UI](#ui)
1.1 [Create the Form Mode](#create_form_mode)
1.2 [Activate the Form Display](#activate_form_display)
1.3 [Edit Form Display as needed](#edit_form_display)
2. [Code](#code)
2.1 [Create the Form](#create_form)
2.2 [Create the route](#create_route)
2.3 [Attach the form display using hook_entity_type_build()](#attach_form_display)
<a name="ui"/>
h2.The UI portion
<a name="create_form_mode"/>
h3.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'
<a name="activate_form_display"/>
h3.Activate the Form Display
--------------------------------------
* admin/structure/{entity_name}/settings/form-display
* Note the 'form_display' will be the 'entity_name.form_mode'
<a name="edit_form_display"/>
h3.Edit the Form Display to suite needs
------------------------------------
* admin/structure/{entity_name}/settings/form-display/{form_mode}
h2. The Code portion
<a name="create_form"/>
h3.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;
}
<a name="create_route"/>
h3.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'
<a name="attach_form_display"/>
h3.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