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

Pizzeria Bianco Pizza https://biancopizza.ru блог о настоящей пицце и итальянской кулинарии. Откройте для себя секреты правильного теста и классические рецепты пиццы!

Permalink

Klikam tu juz jakies dwa miechy, wiec mam juz jakies zdanie. Wpadlem z polecenia kolegi, szukalem czegos z sensownym lobby. Na start rzuca sie w oczy, ze slotow jest duzo — w okolicach 3500 tytulow, glownie Pragmatic Play, Play'n GO, NetEnt i troche Yggdrasil. Klasyki typu Gates of Olympus, Sweet Bonanza czy Book of Dead siedza tam, ale nie ukrywam najwiecej czasu spedzam na Reactoonz.

Pakiet powitalny w Fiery Play Kod Promocyjny wyglada tak: 100 procent do 2000 zl plus 150 darmowych spinow, rozbite na kilka pierwszych wplat. Obrot wynosi x40, co jest norma, choc warto przeczytac warunki — jest tam limit zakladu 5 zl przy odgrywaniu i paru ludzi sie o to potknelo. Kod wbijalem w formularzu rejestracji, bo pozniej kasa leci bez bonusu.

Jak ktos chce sprawdzic aktualne kody, to najlepiej zajrzec do [url=https://leansigma.ai/fieri-play-w-polsce-kompletny-przewodnik-po-kasyni… Play Kod Promocyjny[/url] zanim zalozycie konto, bo akcje rotuja co miesiac. Kraza tez promki bez depozytu, tylko ze trzeba je zlapac.

Live jest ogarniete — ruletki po polsku sa w prime time, no i Crazy Time, Lightning Roulette i ten caly Monopoly Live. Stoly sa od 3 zl, wiec nie trzeba miec grubego portfela. To co mnie denerwuje to w weekendy jest lekki lag na komorce.

Wyplaty z Fiery Play Kod Promocyjny schodza przyzwoicie: Skrill i e-portfele do 3-4 godzin, karta potrafi ciagnac sie 2-3 dni, BTC doslownie w kilkanascie minut. Minimalny depozyt to 60 zl, rejestracja zajmuje doslownie minute, za to weryfikacja przed pierwszym cashoutem zajela mi dobe — dowod plus potwierdzenie adresu. Licencja curacaowska, czyli standard w tym segmencie, ale przelew doszedl bez cyrkow.

Obsluga w Fiery Play Kod Promocyjny gada po polsku na czacie, czekalem jakies kilka minut, konkretnie. Aplikacji nie ma, ale strona mobilna dziala dobrze na Androidzie. Daleko temu do ideal, natomiast siedze dalej i do tej pory nie mialem wiekszych zgrzytow.

Permalink

Obstawiam u nich od jakichs osmiu miesiecy, glownie sloty, wiec podziele sie wrazeniami. Wybor gier w 888starz jest gruby — jakies 3-4 tysiace pozycji, z tym ze czesc to praktycznie te same gry w innych skorkach. Pragmatic Play jest wszedzie — klasyki typu Gates of Olympus sa oblegane, choc osobiscie wole Book of Dead. Jest tez Yggdrasil i Big Time Gaming jak ktos lubi wysoka zmiennosc.

Live to Evolution, wiec wiadomo czego sie spodziewac. Prawdziwi krupierzy, sa nawet polskojezyczne stoly, Crazy Time, Lightning Roulette wieczorem ciezko usiasc. Minus — czasem klatkuje na slabszym necie, choc podejrzewam ze to bardziej moj router.

Startowy bonus w 888starz wynosi 100% do okolo 1500 zl i 150 darmowych spinow, podzielone na pare pierwszych wplat. Warunek obrotu x35 i szczerze mowiac to nie jest bulka z maslem. Byl tez maly bonus bez depozytu po potwierdzeniu konta, raczej na sprobowanie niz na wygrana. Swieze promocje sa opisane na [url=https://smartchoicesmsfadmin.com.au/888starz-kod-bonusowy-szybkie-platn… kod bonusowy – szybkie płatności, wypłaty i bonus powitalny[/url] jak ktos chce porownac. Minimalny depozyt w okolicach 20-25 zl, konto zakladasz w chwile, ale weryfikacje dokumentow zrob od razu.

Kasa z wyplat ida raczej szybko. E-portfele typu Skrill wchodzi mi tego samego dnia, przelew na karte potrafi isc 2-3 dni robocze. Krypto dziala najlepiej — BTC mialem na portfelu w pol godziny. Obsluga 888starz gada po polsku, odpowiedz zwykle w pare minut, z tym ze raz dostalem czyste kopiuj-wklej.

Z telefonu korzystam najwiecej — mobilka chodzi bez zarzutu, ale jest tez 888starz apk do pobrania. Sciagnalem apke bo powiadomienia o promkach, dziala stabilnie. Jedna uwaga — widzialem gdzies podrobione wersje typu apk mod, nie dotykajcie tego, tylko oficjalna wersja. Kasyno ma licencje Curacao — nie jest to unijna, to juz kwestia indywidualna.

Permalink

Котлотрейд https://kotlotrade.ru надежный поставщик промышленного оборудования в Новосибирске. В нашем ассортименте: водогрейные котлы, горелки. Гарантируем качество и выгодные условия. Звоните!

Permalink

An informative Forex blog at https://cryptoforexer.com — here you will learn everything about trading currency pairs, gold, cryptocurrency, and international stocks in 2026, and discover how to create a trading journal that takes just two minutes per trade while actually generating actionable ideas for your future trades.

Permalink

Find more information about VPNs at https://fastvpnservices.com. Fast VPN Services is an independent knowledge base dedicated to virtual private networks and everyday online privacy. We purchase VPN services at retail prices using our own funds, test them on our own hardware, and document the results using a specific methodology alongside the raw data.

Permalink

An independent research group https://theforexbonus.com for experienced FX and digital asset traders. We explain how to build market microstructure and quantitative trading systems, and we fully analyze every bonus before recommending it to you.

Permalink

Полный комплекс услуг https://easyeurodocs.com по оформлению европейских документов «под ключ»: получение ВНЖ, ПМЖ, ID-карт и гражданства в странах ЕС от 10 дней. Юридическое сопровождение, проверка и подготовка пакета документов, решение сложных миграционных задач без очередей. Бесплатная консультация и гарантия прозрачности.

Permalink

Производство металлоконструкций под ключ https://sp-integra.ru. Посетите сайт - проектируем, изготавливаем и монтируем металлоконструкции для промышленных и коммерческих объектов. Берем на себя полный цикл — от расчета до поставки на объект.

Permalink

KinoGo - смотреть фильмы онлайн https://kinoga.pro в хорошем качестве. Новинки кино и популярные сериалы раньше других сайтов. Нет необходимости регистрироваться, также нет ограничений по времени или количеству просмотров.

Permalink

KinoGo - Твой гид https://kinoga.run в мире кино. Онлайн-кинотеатр - только лучшие фильмы, сериалы, мультфильмы и новинки кино в отличном качестве, в том числе для просмотра на ваших портативных гаджетах.

Permalink

Смотреть новинки кино https://kinoga.me быстрее всех приятно вдвойне для каждого. На сайте все что вы ищете сериалы, фильмы, мультики от самых новых до старых фильмов, которые приятно смотреть вновь.

Permalink

KinoGa смотреть фильмы https://kinoga.org онлайн бесплатно на оригинальном КиноГо. Отличное качество с возможностью скачивания, а также смотреть фильмы и сериалы на мобильных устройствах — используя ваш смартфон или планшет.

Permalink

Фильмы онлайн https://kinoga.life смотреть лучшие новинки кино бесплатно в хорошем качестве бесплатно, без регистрации на KinoGo. Все новинки плюс лучшие образцы кинематографа разных эпох. Обширная библиотека, включающая полнометражное и документальное кино, картины в жанрах боевика, триллера, фэнтези и другое.

Add new comment