How to extend an existing Drupal 8 Form
The Use Case
In order to best illustrate the process of extending and existing Drupal 8 Form, we will modify the submit messages for the Simplenews subscribe form.Setup Your Dev Environment
When creating new functionality for your Drupal website, it is always best to use a local development environment. We recommend using Docksal with Docker to accomplish this task because it is simple to setup and includes essential tools for developing with Drupal. We are also going to make sure the contrib module we are modifying is installed and enabled.- Goto Docksal.io and follow install instructions for your Operating System on the OS Support tab to install Docksal with Docker
- Open Terminal/Console
- Create projects directory:
mkdir ~/Sites
- Create project with Docksal:
fin project create
- Name your project & Choose Drupal 8 when prompted (Composer Version is recommended)
- Enter
y
to proceed with setup - Verify you able to access the website using the URL and credentials provided when the install is complete
- Change to your project's directory:
cd ~/Sites/{project_name}
- If the original form is provided by a contributed module, install it:
fin composer require 'drupal/{contrib_project}:^{version}'
and enable it:fin drush en {contrib_project}
Generate Your Custom Module
Now that your local environment is setup, you will need to generate your custom module that will provide the code that will extend the existing form you are modifying. We recommend using Drupal Console to accomplish this task. No need to install Drupal Console because it comes pre-installed with Docksal!- Generate Module:
fin drupal generate:module
NOTE: Do not generate a composer.json file now because it will produce an error
and Enter/yes
when prompted - Generate Composer File:
fin drupal generate:composer
and Enter/yes
when prompted
Locate the Existing Form Code
In this scenario, we are wanting to change the message that displays after subscribing to a newsletter provided by the Simplenews module. Let's look for the original code that generates that message.- Search Files for message:
grep -rl "{message}" .
- Open Project in your favorite file editor. Ex:
bbedit .
- Navigate to file from search in Step 1
- Locate message in file to verify function that needs to be customized.
CTRL(Win)/Command(Mac)+F
Copy and Rename the Form File
The easiest way to limit the number of mistakes is to copy the existing files from the original location into your custom module.- Prepare Destination Folder:
mkdir -p web/modules/custom/{custom_module}/src/Form
- Copy Files:
cp web/modules/contrib/simplenews/src/Form/SubscriptionsBlockForm.php web/modules/custom/{custom_module}/src/Form/
- Rename Files (so unique):
mv web/modules/custom/customize_simplenews_sub_form/src/Form/SubscriptionsBlockForm.php web/modules/custom/{custom_module}/src/Form/SubscriptionsCustomBlockForm.php
- Repeat Steps 2 & 3 for all applicable files in Step 1. NOTE: In this scenario, we did not need to change the file in the Tests directory.
Customize the Form Code
Now we need to modify the Code so that it extends the existing code.- Alter namespace to your Custom module:
namespace Drupal\{custom_module}\Form;
- Add use statement for original code with alias that is same as what was extended in Original Code:
use Drupal\simplenews\Form\SubscriptionsBlockForm as SubscriptionsFormBase;
- Customize Class name to make unique for your module:
SubscriptionsCustomBlockForm
- Remove all code in file, except function located in Step 4 of the Locate the Existing Form Code:
getSubmitMessage()
Before editing code: - Alter code, as needed. Ex:
line 19: return $this->t('This is a different update message.');
Set the Form Handler Class
Almost done coding! Just need to edit the Handler Class for the entity we are modifying.- Add hook to alter entity:
function customize_simplenews_sub_form_entity_type_alter(array &$entity_types)
- Edit handler class for entity:
@var $entity_types \Drupal\Core\Entity\EntityTypeInterface[]
Enable Your Custom Module
Congrats! The coding is over! Now, just enable the module, refresh and test to verify.- Verify system sees module:
fin drush pml | grep {custom_module}
- Enable the Custom Module:
fin drush en {custom_module}
- If warning encountered during enable:
- Disable the Custom Module:
fin drush pmu {custom_module}
- Open the custom modules composer.json file:
bbedit ~/Sites/{custom_module}/composer.json
- Remove extra comma in require section & Save changes.
- Enable the Custom Module:
fin drush en {custom_module}
- Disable the Custom Module:
- Revisit Subscription Page Verify Changes. NOTE: If this is a fresh install, you may need to add the simplenews block to the sidebar.
Congrats!
You have successfully extended and existing form programmatically the "Drupal way". Hopefully, this introduction to extending Drupal code has provided you with a simple use case that will help you to continue extending other code. If you ever get stuck, please don't hesitate to contact us or sign-up for a mentoring session.ABOUTME
I was hippie-born, raised on Science and Invention on a nuclear mesa, SCAdian before I knew the Society, Technomancer before I played the game, creative genius breaking the shackles of Corporate America.
Owner of tekAura, an Information Technology & Design Consultancy involved in projects concerning Human Dynamics & Sustainability in relation to Computing and Technology, Collective creativity & Hackerspaces, SaaS & Cloud Computing, Home & Manufacturing Automation.
Artfully applies Sustainability, Disaster Recovery, Open Source and Agile Industry Best Practices to boost innovation and facilitate Organic Collaboration and Continuous Process Improvement.
I’m the with regard to the majority of the content pieces, We completely savored, I'd truly choose much more information concerning this particular, considering the fact that it is good., Thanks intended for publishing. kmspico
ReplyDeleteThanks
ReplyDeleteفرقة دبا لليولة
Goooooood
ReplyDeletehafedkplus
This comment has been removed by a blog administrator.
ReplyDeleteThis is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
ReplyDeletePMP Certification
PMP Course
PMP Course in malaysia
PMP Training in malaysia
PMP Training
Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
ReplyDeletedata analytics course
big data analytics malaysia
big data course
I'm happy to see the considerable subtle element here!.
ReplyDeletedata science course
Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. pmp certification
ReplyDeletepmp course
pmp Training
pmp course in Malaysia
pmp Training in Malysia
I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.data science course
ReplyDeleteAwesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
ReplyDeletedata analytics course
big data analytics malaysia
big data course
The team was responsive and had good communication skills. digital design agencies - they remained dedicated to the client.
ReplyDeleteWell, it’s a nice one, I have been looking for. Thanks for sharing such informative stuff.
ReplyDeletebulk url opener
Thank you for the information.... Ahrefs Group Buy is famous for its tool worldwide. One can get the best deals for the tool at a cheap price
ReplyDeleteThanks for the information.... Ahrefs Group Buy is one of the best tool provider in the world.
ReplyDeleteGreat Article IoT Projects for Students
ReplyDeleteDeep Learning Projects for Final Year
JavaScript Training in Chennai
JavaScript Training in Chennai
The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training