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

Napdoku: Cozy Brain Puzzle 猫 パズル is a relaxing logic game designed for brain training and unwinding. Solve number puzzles to sharpen your attention, concentration, and logical thinking skills as you progress through increasingly challenging levels.

Permalink

Интернет-магазин https://www.minds.com/group/1969786005129007104/latest лицензионного софта и цифровых товаров предлагает широкий выбор программ для работы, бизнеса и дома. Покупайте официальные лицензии, антивирусы, офисные приложения и цифровые продукты по доступным ценам.

Permalink

Онлайн-журнал https://profile.google.com/@tour.out о luxury travel и путешествиях со вкусом. Узнавайте о лучших отелях, частных виллах, яхтинге, авиации, гастрономических маршрутах и wellness-курортах. Вдохновляйтесь идеями для незабываемого отдыха.

Permalink

Want to download Angry Birds الطيور الغاضبة for your smartphone or tablet? Check out this popular arcade game—launch birds from a slingshot, demolish structures, and beat engaging levels. Learn about the different versions of the game and how to install them.

Permalink

Ищете, где получить получить сертификат ГОСТ Р ИСО 9001? Мы поможем организовать процесс сертификации, разобраться в требованиях стандарта, подготовить необходимые документы и пройти оценку системы менеджмента качества.

Permalink

Want to download Angry Birds 愤怒的小鸟 for your smartphone or tablet? Check out this popular arcade game—launch birds from a slingshot, demolish structures, and beat engaging levels. Learn about the different versions of the game and how to install them.

Permalink

Ищете, где получить получить сертификат ISO 9001? Мы поможем организовать процесс сертификации, разобраться в требованиях стандарта, подготовить необходимые документы и пройти оценку системы менеджмента качества.

Permalink

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

Permalink

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

Permalink

Нужен забор? https://www.zabor-dlya-dachi-evroshtaketnik-metallicheskiy.ru/uslugi/za… для участков любой площади. Предлагаем широкий выбор конструкций, материалов и вариантов оформления. Изготовим ограждение по индивидуальному проекту, согласуем цену и выполним установку на вашем участке.

Permalink

Компания FarbWood https://farbwood.by предлагает пиломатериалы из сибирской лиственницы для частного и коммерческого строительства в Минске и по всей территории Беларусь.

Permalink

Сервисная поддержка сайтов https://servisnaya-podderzhka.ru профессиональная помощь в обслуживании, обновлении и доработке веб-ресурсов. Закажите технические работы, исправление ошибок, настройку функционала, оптимизацию и сопровождение сайта.

Permalink

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

Permalink

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

Permalink

Сервисная поддержка сайтов https://servisnaya-podderzhka.ru профессиональная помощь в обслуживании, обновлении и доработке веб-ресурсов. Закажите технические работы, исправление ошибок, настройку функционала, оптимизацию и сопровождение сайта.

Permalink

Слышал витражи по технике фьюзинг будто это просто склеенные кусочки. На самом деле стекло спекают в печи при 750–850°С, и важно, чтобы коэффициенты температурного расширения совпадали. Подробности процесса и разновидности спекания есть на странице.

Permalink

Замечено: оформление шарами детского праздника. Родители часто выбирают фигуры из шаров и акции для мальчиков и девочек. На странице есть и отдельные шары с гелием — удобно, если нужен небольшой акцент, а не целая композиция.

Permalink

Заметила: мебель от производителя. В обсуждениях часто хвалят местных производителей за возможность подогнать мебель под нишу или нестандартную планировку. На bigmebel-komsomolsk.ru представлены кухни, шкафы-купе и гардеробные, которые можно заказать по своим размерам.

Permalink

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

Permalink

Сравнение цветы в лимассол на кипре двух вариантов: готовый букет или корзинка. Корзинки из роз, лилий, гербер, ирисов, тюльпанов и хризантем выглядят устойчивее и дольше стоят. Выбирайте по поводу и получателю, а перед заказом уточните город и пожелания.

Permalink

взять займ на карту процентов заем на кредитную карту срочно

Permalink

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

Permalink

Проектирование сетевой инфраструктуры https://network-serv.ru для офисов, предприятий и коммерческих объектов. Разрабатываем схемы локальных сетей, подбираем оборудование, рассчитываем нагрузку и обеспечиваем надежную основу для стабильной работы IT-систем.

Permalink

Проектирование сетевой инфраструктуры https://network-serv.ru для офисов, предприятий и коммерческих объектов. Разрабатываем схемы локальных сетей, подбираем оборудование, рассчитываем нагрузку и обеспечиваем надежную основу для стабильной работы IT-систем.

Permalink

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

Permalink
Permalink

cheap amoxicillin 500mg and cost of amoxicillin prescription generic amoxicillin
http://urlaubhamster.de/out.php?link=http://getsynapsefuel.com amoxicillin 500 mg for sale and https://brueckrachdorf.de/user/ssxreymvzh/ amoxicillin online canada
buy amoxicillin online cheap can i purchase amoxicillin online or amoxicillin 500mg no prescription can you buy amoxicillin over the counter canada

Add new comment