Creating Custom Content Types Programmatically in Drupal 10

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:

  1. A working Drupal 10 or 9 website.
  2. Basic knowledge of Drupal site building and module development.
  3. 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:

  1. In your Drupal installation, navigate to the sites/all/modules directory (or your preferred module location).
  2. Create a new directory for your custom module. Give it a unique and descriptive name, such as my_custom_content_type.
  3. 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:
  - node

This 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.

  1. Create a file named my_custom_content_type.module in your module directory.
  2. 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.

  1. 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

  1. In your Drupal admin interface, navigate to Extend (admin/modules) and enable your custom module, "My Custom Content Type Module."
  2. 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.

Share on social media

Comment

Permalink

Відвідайте сайт https://akkb.top і ви знайдете за вигідними цінами Li-ion та LiFePO4 акумулятори, готові зборки для електротранспорту та резервного живлення, зарядні та BMS. AKKB.top: відправка Новою поштою по всій Україні. Ми не тільки продаємо акумулятори: проектуємо, збираємо та відновлюємо батареї для обладнання, транспорту та будинку.

Permalink

Консультация нутрициолога онлайн https://natralab.ru : разбор анализов, оценка образа жизни и коррекция питания. На основе анкеты и результатов анализов — персональная программа питания с учётом ваших целей и привычек. Составление индивидуального плана питания онлайн, рекомендации для поддержания энергии и персональная wellness-программа. Запишитесь на консультацию на сайте

Permalink

Посетите сайт https://kramarovskiyonair.ru и вы сможете выбрать удобную для вас платформу чтобы смотреть новости от Ильи Крамаровского. Обзоры мировых СМИ в удобном формате, свежие выпуски на любой платформе. Крамаровский пояснит любые события в мире - подробно и доступно.

Permalink

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.

Permalink

СоюзВоенТорг https://souzvoentorg.ru - интернет-магазин военного снаряжения и амуниции для профессионалов и любителей. В каталоге представлены FPV-дроны и квадрокоптеры с тепловизорами, детекторы и подавители БПЛА, рации, усилители связи, бронежилеты, шлемы, тактическая экипировка и аксессуары. Работаем напрямую с производителями, предлагаем выгодные оптовые цены, индивидуальный подбор комплектов, бесплатную доставку по России, гарантию до 12 месяцев и консультации по выбору оборудования.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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

Permalink

Посетите сайт бездепозитные бонусы и вы найдете бездепозитные бонусы за регистрацию в казино с выводом без пополнения, а также прочие бонусы которые можно получить от различных казино. Ознакомьтесь с полной информацией на сайте.

Permalink

Посетите сайт мебель на заказ во владимире - это Modus Style мебельная фабрика и салон корпусной мебели по индивидуальным размерам во Владимире. Широкий ассортимент: кухни, шкафы-купе, распашные и мансардные шкафы, гардеробные, детские, прихожие, гостиные, спальни, столы, тумбы и кровати.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Permalink

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.

Add new comment