Content types are the backbone of content management in Drupal. In Drupal 10, you can create custom content types to structure and organize your content. This blog post will guide you through the process of creating content types programmatically in Drupal 10, allowing you to tailor your website's content structure to your specific needs.
Prerequisites
Before creating custom content types programmatically in Drupal 10, you should have the following:
- A working Drupal 10 or 9 website.
- Basic knowledge of Drupal site building and module development.
- Familiarity with PHP and Drupal's module structure.
Step 1: Define the Custom Module
To create a custom content type programmatically, you need to place the code in a custom module. If you don't already have a custom module, you can create one by following these steps:
- In your Drupal installation, navigate to the sites/all/modules directory (or your preferred module location).
- Create a new directory for your custom module. Give it a unique and descriptive name, such as my_custom_content_type.
- Inside your module directory, create a my_custom_content_type.info.yml file with the following content:
name: 'My Custom Content Type Module'
type: module
description: 'Defines custom content types programmatically.'
core_version_requirement: ^9 || ^10
package: Custom
dependencies:
- nodeThis YAML file defines the basic information about your custom module.
Step 2: Create a Custom Content Type
To create a custom content type, you'll need to implement the hook_entity_type_build and hook_node_type_insert hooks within your custom module.
- Create a file named my_custom_content_type.module in your module directory.
- In this file, implement the hook_entity_type_build hook to define your custom content type. Here's an example:
/**
* Implements hook_entity_type_build().
*/
function my_custom_content_type_entity_type_build(array &$entity_types) {
$entity_types['node']->setClass('Drupal\my_custom_content_type\NodeTypeCustom');
}This code defines a custom class, NodeTypeCustom, to handle the configuration of your custom content type.
- Create the NodeTypeCustom class in a file named NodeTypeCustom.php and place it in your module's directory:
namespace Drupal\my_custom_content_type;
use Drupal\node\NodeTypeBase;
/**
* Provides a custom content type.
*/
class NodeTypeCustom extends NodeTypeBase {
/**
* {@inheritdoc}
*/
public function postSave(NodeTypeInterface $node_type) {
parent::postSave($node_type);
// Define the custom content type settings.
$config = \Drupal::configFactory()->getEditable('node.type.' . $node_type->id());
$config->set('name', 'Custom Content Type');
$config->set('description', 'A custom content type created programmatically.');
$config->set('new_revision', TRUE);
$config->save();
}
}n the NodeTypeCustom class, we extend the NodeTypeBase class to define the custom content type settings, such as the name and description.
Step 3: Enable and Verify Your Custom Content Type
- In your Drupal admin interface, navigate to Extend (admin/modules) and enable your custom module, "My Custom Content Type Module."
- After enabling the module, go to Structure > Content types (admin/structure/types) to see your custom content type listed as "Custom Content Type."
Conclusion
Creating custom content types programmatically in Drupal 10 allows you to define content structures that fit your specific project requirements. By following the steps outlined in this blog post, you can easily create and configure custom content types within your Drupal website, providing a flexible and tailored content management experience.
In Drupal 9 and 10, custom modules should be stored in the "modules/custom" directory rather than "sites/all/modules." Drupal's module directory structure has evolved, and the recommended practice is to place custom modules in the "modules/custom" directory to follow the modern Drupal standards.
So, if you're creating a custom module in Drupal 9 or 10, you should place it in the following directory:
/sites/all/modules/custom/By following this structure, your custom modules will be more organized and adhere to Drupal's best practices, making it easier to manage and maintain your site's codebase.
Comment
medicine online order online…
medicine online order online pharmacy no prescription needed trusted online pharmacy
Відвідайте сайт https://akkb…
Відвідайте сайт https://akkb.top і ви знайдете за вигідними цінами Li-ion та LiFePO4 акумулятори, готові зборки для електротранспорту та резервного живлення, зарядні та BMS. AKKB.top: відправка Новою поштою по всій Україні. Ми не тільки продаємо акумулятори: проектуємо, збираємо та відновлюємо батареї для обладнання, транспорту та будинку.
Консультация нутрициолога…
Консультация нутрициолога онлайн https://natralab.ru : разбор анализов, оценка образа жизни и коррекция питания. На основе анкеты и результатов анализов — персональная программа питания с учётом ваших целей и привычек. Составление индивидуального плана питания онлайн, рекомендации для поддержания энергии и персональная wellness-программа. Запишитесь на консультацию на сайте
Посетите сайт https:/…
Посетите сайт https://kramarovskiyonair.ru и вы сможете выбрать удобную для вас платформу чтобы смотреть новости от Ильи Крамаровского. Обзоры мировых СМИ в удобном формате, свежие выпуски на любой платформе. Крамаровский пояснит любые события в мире - подробно и доступно.
https://bactribatchindia.com…
https://bactribatchindia.com/# buy antibiotics for sinus
buy drugs online or pharmacy…
buy drugs online or pharmacy websites no prescription pharmacy paypal
https://maps.google.je/url?sa=t&url=https://getscriptkinetics.xyz п»їinternational drug martand http://la-maison-des-amis.com/user/ookaeejeaw/ online pharmacy
medicine online online pharmacy without scriptsor online pharmacy no rx reputable overseas online pharmacies
antibiotics online pharmacy:…
antibiotics online pharmacy: bactribatch indian pharmacy - otc uti medicine
Aktis House is a Greek https…
Aktis House is a Greek https://aktis.house real estate developer specializing in premium villas, luxury apartments and investment properties. From land selection and architectural design to construction, furnishing and property management, we deliver turnkey real estate solutions in Thessaloniki, Halkidiki and Athens.
СоюзВоенТорг https:/…
СоюзВоенТорг https://souzvoentorg.ru - интернет-магазин военного снаряжения и амуниции для профессионалов и любителей. В каталоге представлены FPV-дроны и квадрокоптеры с тепловизорами, детекторы и подавители БПЛА, рации, усилители связи, бронежилеты, шлемы, тактическая экипировка и аксессуары. Работаем напрямую с производителями, предлагаем выгодные оптовые цены, индивидуальный подбор комплектов, бесплатную доставку по России, гарантию до 12 месяцев и консультации по выбору оборудования.
GR Estate https://gr.estate…
GR Estate https://gr.estate is a catalog of new-build homes in Greece: villas and apartments in Halkidiki, Athens, Thessaloniki and beyond. Every project is checked, rated by class and compared on price per m?. Zero commission for buyers, plus turnkey furnishing, rental management, remote purchase support and Golden Visa guidance. Compare before you buy.
Explore Greece’s Golden Visa…
Explore Greece’s Golden Visa https://goldenvisa.estate through carefully selected real estate investments. Goldenvisa.estate offers end-to-end support with property selection, legal due diligence, purchase and residency applications for you and your family. Discover homes in Athens, Thessaloniki, Halkidiki.
ИИ фотосессия с мамой https:…
ИИ фотосессия с мамой https://ai-photosessions.ru
ИИ фотосессия по фото https:…
ИИ фотосессия по фото https://ai-photosessions.ru
AKTIS STONE https:/…
AKTIS STONE https://flexiblestone.gr - flexible ceramic cladding made from 100% natural clay, just 3mm thin, in 400+ textures. A lightweight, fireproof and waterproof alternative to natural stone for facades and interior walls. Easy to install on almost any surface — eco-friendly, durable and stylish. Available in Thessaloniki and Athens, with delivery across Greece.
Spin Formula Casino https:/…
Spin Formula Casino https://formulaspin.net is a standout for UK players who value variety. With games from 92 providers, the lobby brings together jackpot slots and live dealer favourites like blackjack, roulette and baccarat. English-language live chat is available 24/7.
Aktis Home https://aktis…
Aktis Home https://aktis.design - your one-stop shop for interior design and premium furniture in Greece. Browse designer furniture, modern lighting, decor and outdoor pieces, plus turnkey design, home staging and rental-ready furnishing. We create 3D interiors and bring them to life. Available in Thessaloniki, Halkidiki and Athens, with delivery across Greece.
Строительный консалтинг…
Строительный консалтинг https://stroyprav.pro и профессиональное управление строительными проектами. От проектирования до ввода в эксплуатацию.
Фотосессия ИИ онлайн https:/…
Фотосессия ИИ онлайн https://ai-photosessions.ru
Мужская фотосессия ИИ https:…
Мужская фотосессия ИИ https://www.ai-photosessions.ru
ИИ фотосессия пары https:/…
ИИ фотосессия пары https://ai-photosessions.ru/
Over the counter antibiotics…
Over the counter antibiotics for infection: bactribatch indian pharmacy - buy antibiotics for sinus
Фотосессия ИИ https://ai…
Фотосессия ИИ https://ai-photosessions.ru/
get ed meds today:…
get ed meds today: BorealVigorCanada - online ed pharmacy
international pharmacy or…
international pharmacy or shop medicine online international pharmacy
https://images.google.com.sv/url?q=https://getscriptkinetics.com shop medicine online or https://boyerstore.com/user/psguwpuiho/?um_action=edit online drugs order
overseas online pharmacy best rx pharmacy online and best mail order pharmacy best rx pharmacy online
http://getscriptkinetics.com…
http://getscriptkinetics.com/# no prescription pharmacy paypal
best online pharmacy:…
best online pharmacy: discount generic medications online - online pharmacy no prescription
https://getscriptkinetics…
https://getscriptkinetics.xyz/# п»їinternational drug mart
https://getscriptkinetics…
https://getscriptkinetics.com/# worldwide pharmacy online
buying erectile dysfunction…
buying erectile dysfunction pills online: BorealVigorCanada - pills for ed online
online ed medications: ed…
online ed medications: ed pills canadian pharmacy - erectile dysfunction online prescription
legitimate online pharmacy…
legitimate online pharmacy or best online pharmacy no prescription online pharmacy no rx
http://hlsw.org/ajax/news_slides/default.php?link=https://getscriptkine… us pharmacy no prescription and https://allchoicesmatter.org/user/uoluqvqeer/?um_action=edit п»їinternational drug mart
international pharmacy online pharmacies and trustworthy online pharmacy reputable online pharmacy no prescription
antibiotics for uti or buy…
antibiotics for uti or buy antibiotics from india antibiotics online pharmacy
https://maps.gngjd.com/url?q=https://bactribatchindia.com over the counter antibiotics pills or http://www.1gmoli.com/home.php?mod=space&uid=1344084 antibiotics for uti
buy antibiotics online antibiotics for uti or get antibiotics quickly antibiotic without presription
http://bactribatchindia.com/…
http://bactribatchindia.com/# over the counter antibiotics
secure medical online…
secure medical online pharmacy and best rx pharmacy online no script pharmacy
https://www.google.com.ua/url?q=https://getscriptkinetics.xyz safe online pharmaciesand https://www.trendyxxx.com/user/ptlcyiffpt/videos buy drugs online
=Viagra+generic]trustworthy online pharmacy best rx pharmacy onlineor medicine online online pharmacy without scripts
buy online medicine: no…
buy online medicine: no script pharmacy - no script pharmacy
http://borealvigorcanada.com…
http://borealvigorcanada.com/# buying erectile dysfunction pills online
Посетите сайт бездепозитные…
Посетите сайт бездепозитные бонусы и вы найдете бездепозитные бонусы за регистрацию в казино с выводом без пополнения, а также прочие бонусы которые можно получить от различных казино. Ознакомьтесь с полной информацией на сайте.
Посетите сайт мебель на…
Посетите сайт мебель на заказ во владимире - это Modus Style мебельная фабрика и салон корпусной мебели по индивидуальным размерам во Владимире. Широкий ассортимент: кухни, шкафы-купе, распашные и мансардные шкафы, гардеробные, детские, прихожие, гостиные, спальни, столы, тумбы и кровати.
Имплантация зубов https:/…
Имплантация зубов https://stomos.ru/uslugi/implantatsiya_zubov в Москве. Клиника Доктора Осипова. Работаем с 2003 года.
ed medication online:…
ed medication online: borealvigor canadian pharmacy - ed meds by mail
https://borealvigorcanada…
https://borealvigorcanada.com/# where can i buy erectile dysfunction pills
online pharmacy without…
online pharmacy without prescription or foreign online pharmacy buy drugs online
https://images.google.com.iq/url?q=https://getscriptkinetics.com buy drugs online and https://kamayegaindia.com/user/uhwgnubpuf/?um_action=edit legal online pharmacy
online pharmacies worldwide pharmacy online and new pharmacy online foreign online pharmacy
cheap boner pills:…
cheap boner pills: borealvigor canadian pharmacy - online erectile dysfunction prescription
https://getscriptkinetics…
https://getscriptkinetics.com/# online pharmacy discount code
For creators considering buy…
For creators considering buy likes on tiktok, clear limits and a consistent measurement window make the test easier to interpret. Before ordering, compare delivery pace, retention terms, refill policy, and support response time, and ask how the company handles delays, partial delivery, or unexpected drops. Watch for an abrupt spike that does not match the account's normal reach, and use watch time, completion rate, shares, saves, and profile visits to decide whether the test added anything beyond a larger visible number.
When people look for buy…
When people look for buy views on youtube, the most useful first step is separating a visibility test from a growth strategy. Compare providers by the clarity with which they review traffic sources, delivery timing, audience geography, refund rules, and reporting access, not by testimonials or the largest advertised bundle. The account owner should still prioritize useful titles, accurate thumbnails, strong openings, and a consistent publishing plan and review average view duration, retention, clicks, comments, and subscriptions; this keeps the result in proportion.
For a small Twitter/X…
For a small Twitter/X experiment, buy real twitter followers should be assessed with a fixed budget and a written test plan. Start by asking how they check delivery speed, profile quality, replacement coverage, privacy requirements, and cancellation terms; specific procedures are more informative than claims about being the best. Avoid scaling after one attractive screenshot. Review impressions, replies, reposts, link clicks, and follower retention and check for a sudden follower increase with no matching activity on the timeline across several days.
A careful comparison of…
A careful comparison of where to buy instagram views starts with the account's present audience, content pattern, and normal reach. Compare providers by the clarity with which they compare gradual delivery, retention guarantees, refill conditions, support quality, and account-data requirements, not by testimonials or the largest advertised bundle. Measure retention, shares, saves, profile visits, and follows against the original baseline, because a large instant jump followed by visible drops a few days later can make a weak service appear successful at first.
The best starting point for…
The best starting point for buy tiktok likes is a modest campaign tied to one post and one review period. The provider should be able to compare delivery pace, retention terms, refill policy, and support response time without guaranteeing viral reach, revenue, or permanent account growth. If the campaign produces an abrupt spike that does not match the account's normal reach, pause the experiment and return attention to strong hooks, clear captions, consistent posting, and audience-specific creative before spending more.
A transparent provider for…
A transparent provider for buy youtube views should make its process, timing, and support terms understandable before payment. A useful vendor screen is to review traffic sources, delivery timing, audience geography, refund rules, and reporting access while checking whether the written policy matches the checkout page. Keep the order separate from other campaigns, then compare average view duration, retention, clicks, comments, and subscriptions with the baseline before repeating it.
Pagination
Add new comment