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

Безмолвие наступило :)
юридическая помощ, [url=https://pol-servis.net/forum/user/4628/]https://pol-servis.net/forum/us…] необходима каждому в сложных ситуациях. Опытный юрист обеспечит поддержку в разрешении правовых вопросов. Важно обращаться за консультациями, чтобы избежать риски и ошибки.

Permalink

Нуждаетесь в идеальном месте для вечера ресторан с караоке https://karaokespb.vercel.app для праздника. Среди представленных вариантов доступны для сравнения клубы с музыкальными программами. Оцените условия бронирования. Для семейного праздника удобно выбрать место с подходящей атмосферой. Планируете музыкальную вечеринку? Выберите подходящее место и собирайте друзей.

Permalink

Изучим темой https://volga.news/805142/article/chem-frontalnyj-pogruzchik-otlichaetsya-ot-drugoj-skladskoj-i-stroitelnoj-tehniki.html и принципом работы. Такие машины задействуются на производственных площадках. Основным рабочим органом выступает ковш, который позволяет загружать грунт. При сравнении техники обычно учитывают грузоподъемность. Дополнительную информацию об устройстве, характеристиках и применении техники можно найти в статье.

Permalink

Подбираете караоке-клуб https://karaokespb.vercel.app для корпоративного отдыха. На странице отобраны караоке-комнаты. Подберите стоимость посещения. Для семейного праздника несложно отыскать подходящее заведение. Ищете место для компании? Посмотрите доступные варианты и отправляйтесь на отдых.

Permalink

Рассмотрим устройством https://volga.news/805142/article/chem-frontalnyj-pogruzchik-otlichaetsya-ot-drugoj-skladskoj-i-stroitelnoj-tehniki.html и особенностями эксплуатации. Такие машины применяются в сельском хозяйстве. Важной частью конструкции является рабочий ковш, который позволяет перемещать щебень. При сравнении техники обычно учитывают объем ковша. Дополнительную информацию об устройстве, характеристиках и применении техники можно найти в статье.

Permalink

Для тех, кто интересуется дом https://castor-mebel.ru поможет найти практические рекомендации. В новых материалах разбираются идеи оформления интерьера. Можно узнать какие решения подходят для разных помещений. Читайте материалы и находите идеи для обустройства комфортного интерьера.

Permalink

Тем, кто увлекается уходом за собой https://russkajakrasota.ru будет интересен полезные материалы. В разделах разбирают модные тенденции. Стоит почитать практические рекомендации. Читайте интересующие материалы и находите новые идеи для ухода, стиля и повседневной жизни.

Permalink

Если хочется изменить квартиру https://castor-mebel.ru содержит тематические публикации. В новых материалах рассматриваются идеи оформления интерьера. Стоит почитать как организовать пространство. Сравнивайте материалы и находите идеи для обустройства комфортного интерьера.

Permalink

Для тех, кто занимается дизайном интерьера https://mebel-lotos18.ru будет полезен тематическим публикациям. На страницах ресурса разбираются строительные решения. Можно узнать какие решения подходят для дома. Читайте подходящие материалы и находите практические идеи для ремонта и обустройства жилья.

Permalink

Тем, кто изучает аренду жилья https://ru-nedvizhimost.ru будет полезен актуальным предложениям. Среди объявлений можно найти жилые объекты. Перед покупкой рекомендуется проверить стоимость. Просматривайте подходящие объявления и находите варианты недвижимости под свои задачи.

Permalink

Если интересует ремонтом https://mebel-lotos18.ru будет полезен практическим материалам. На сайте публикуются советы по дому. Полезно изучить как выбрать материалы. Читайте подходящие материалы и находите практические идеи для ремонта и обустройства жилья.

Permalink

Для тех, кто занимается продажу недвижимости https://ru-nedvizhimost.ru может пригодиться информации об объектах. В базе представлены дома. Во время поиска подходящего объекта стоит учитывать стоимость. Выбирайте подходящие объявления и находите варианты недвижимости под свои задачи.

Permalink

Bazzico su Crazy Time ormai da quattro o cinque mesi, allora ha senso buttare giu qualcosa siccome qui qualcuno chiedeva. Non e la recensione perfetta, giusto come e andata a me.

Quello che mi ha convinto all'inizio e la sezione con i croupier veri. Ci sono tutti i game show, roulette con tavoli italiani in fascia serale, e chiaramente il gioco della ruota con i quattro bonus. Sulle slot parliamo di 2.000 giochi: i soliti Pragmatic con Gates of Olympus e Sweet Bonanza, il vecchio Book of Dead di Play'n GO, qualcosa di NetEnt, Betsoft e Yggdrasil. Non e un catalogo infinito, pero il grosso c'e.

Il pacchetto di benvenuto che offre Crazy Time quando mi sono iscritto era un 100% fino a 500€ e poi 150 free spin spalmati su qualche giorno. Il wagering e il solito 35x, cosa che non e regalato pero e nella media del mercato. Ho beccato pure dei free spin senza deposito ma le condizioni cambiano, per cui conviene guardare l'offerta del momento direttamente su [url=https://www.inside360.agency/2026/09/23/crazy-time-apk-recensione-compl… Time APK: recensione completa, bonus, installazione sicura e gioco mobile in Italia[/url] prima di registrarti.

Il minimo per depositare 20€, iscrizione con SPID e documento — da me e passata in 24 ore, a un tizio che conosco due. Carte passano senza storie, Skrill e Neteller sono i piu veloci, hanno aggiunto anche le crypto ma non l'ho provato. I prelievi fatti su Crazy Time hanno impiegato uno o due giorni sull'e-wallet, sul bonifico si va a 4 giorni lavorativi.

Quello che non mi e piaciuto: manca l'applicazione nativa, solo il sito da browser. Funziona dignitosamente su Android, ma con qualche titolo mi si e impallato e ho dovuto ricaricare. La chat di casa Crazy Time risponde in italiano sempre disponibile, tempi sui 5 minuti, pero la prima risposta e un template. Licenza c'e la MGA — per noi in Italia va tenuto presente, valuta tu.

Permalink

Bazzico su Crazy Time ormai da un paio di stagioni, allora ha senso buttare giu qualcosa siccome qui se ne parlava. Non voglio fare il pistolotto, semplicemente quello che ho visto io.

La cosa che mi ha preso subito e la roba di Evolution. Trovi gli show, roulette con tavoli italiani in fascia serale, e ovviamente la ruota con i quattro bonus. Lato slot parliamo di 2.000 titoli: i soliti Pragmatic tipo Gates of Olympus e Sweet Bonanza, Play'n GO, qualcosa di NetEnt, Yggdrasil. Non hanno tutto, ma il grosso c'e.

Il pacchetto di benvenuto su Crazy Time quando mi sono iscritto era il classico 100% fino a 300€ con in aggiunta 200 giri gratis spalmati su qualche giorno. Il wagering e 35x, che non e una passeggiata pero e nella media del mercato. C'erano anche dei free spin senza deposito pero ruota di continuo, quindi meglio controllare i termini attuali direttamente su [url=http://yorkvillagefire.com/crazy-time-download-guida-completa-per-l-ita… Time download: guida completa per l'Italia[/url] prima di registrarti.

Il minimo per depositare 10 euro, iscrizione con SPID e documento — a me hanno verificato in un giorno, a un amico quasi tre. Le carte vanno senza problemi, gli e-wallet tipo Skrill sono i piu rapidi in uscita, hanno aggiunto anche le crypto ma non l'ho usato. I prelievi da Crazy Time hanno impiegato uno o due giorni via e-wallet, con bonifico ci vogliono 3-4 giorni.

Quello che non mi e piaciuto: manca l'applicazione nativa, solo il sito da browser. Funziona dignitosamente su Android, ma su alcune slot ha fatto i capricci costringendomi a riavviare. La chat di casa Crazy Time parla italiano ed e attiva h24, tempi di 3-5 minuti, pero la prima risposta e un template. Lato licenza c'e quella di Curacao — per un giocatore italiano va tenuto presente, ognuno si regola.

Permalink

Откройте популярное https://online-casino-polsha.info для игры. Откройте слотам и выберите понравившуюся игру. В игровом разделе представлены разные игровые категории. Ищете новую площадку? Переходите к регистрации. Перед регистрацией проверьте правила, возрастные требования и доступность сервиса в вашем регионе. Играйте ответственно.

Permalink

canadian pharmacy official site and reliable canadian pharmacy cipa canada online pharmacy
https://www.google.bs/url?q=https://canamcrosscare.com canadian pharmacy website and http://www.1gmoli.com/home.php?mod=space&uid=1108478 canadian pharmacies that ship to usa
canadian pharmacies that deliver to the us legitimate canadian online pharmacy or canadian pharmacies that ship to usa certified canadian pharmacy

Add new comment