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

1C-Bitrix: Управление сайтом — редакция Стандарт — это мощная платформа для создания и управления корпоративными сайтами. Переходите по запросу Битрикс Стандарт цена. Подходит для компаний, которым нужен функциональный сайт с каталогом, формами, SEO-инструментами и удобной системой администрирования. Решение обеспечивает высокую безопасность, производительность и гибкость масштабирования бизнеса в интернете.

Permalink

Санитарные системы https://bio-ecopro.ru для мероприятий и стройплощадок — аренда мобильных туалетов, умывальников и санитарных модулей. Доставка, обслуживание и вывоз. Надежные решения для фестивалей, концертов, стройки и массовых событий.

Permalink

Менопауза и перименопауза https://menopower.ru симптомы, приливы и гормональные изменения. Полезные советы для женщин 45+, рекомендации по здоровью, образу жизни и управлению финансами для комфортного прохождения этого периода.

Permalink

Компания DARKLUM https://darklum.ru/catalogue предлагает широкий ассортимент светодиодных светильников различного назначения для коммерческих и жилых помещений как внутреннего, так и уличного освещения. В каталоге представлено более 5 000 моделей различных форм-факторов, среди которых Вы без труда сможете выбрать оптимальный вариант.

Permalink

Проверенные адвокаты Москвы https://isk1.ru квалифицированная юридическая помощь и защита в суде. Решение сложных правовых споров, сопровождение дел и профессиональный подход к каждому клиенту для достижения результата.

Permalink

PUPIL OF FATE MOTORS https://auto.ae/pupiloffatemotors автосалон премиум авто в Дубае. Продажа роскошных автомобилей, эксклюзивные модели и индивидуальный подбор. Помогаем выбрать, оформить и доставить авто с гарантией качества и высоким уровнем сервиса.

Permalink

Modern ground fault sensor monitor the condition of electrical networks and protect equipment. They offer rapid fault detection, high accuracy, and reliability for industrial applications.

Permalink

PUPIL OF FATE MOTORS https://auto.ae/pupiloffatemotors автосалон премиум авто в Дубае. Продажа роскошных автомобилей, эксклюзивные модели и индивидуальный подбор. Помогаем выбрать, оформить и доставить авто с гарантией качества и высоким уровнем сервиса.

Permalink

Эко-бытовая химия http://reporter63.ru/content/view/784903/himiya-dlya-uborki-sekrety-eff… в Санкт-Петербурге — средства для уборки без вредных компонентов. Эффективная очистка, безопасность для здоровья и окружающей среды. Широкий ассортимент и доставка по городу.

Permalink

Modern ground fault sensor monitor the condition of electrical networks and protect equipment. They offer rapid fault detection, high accuracy, and reliability for industrial applications.

Permalink

Купить стройматериалы https://stroyrostov161.ru в Ростове-на-Дону: широкий выбор сыпучих и строительных материалов, включая щебень, песок, цемент, штукатурку и шпатлевку. Быстрая доставка и доступные цены для вашего объекта.

Permalink

Заборы под ключ https://dachnie-zabory.ru в Москве и области — изготовление и установка ограждений для дома и участка. Профнастил, штакетник, сетка рабица и 3D заборы. Замер, доставка и монтаж с гарантией качества и соблюдением сроков.

Permalink

Битрикс: Управление сайтом Малый Бизнес — функциональная редакция CMS для создания интернет-магазинов и коммерческих проектов. Переходите по запросу 1С Битрикс Малый Бизнес. Система включает каталог товаров, корзину, онлайн-оплаты, маркетинговые инструменты и интеграцию с 1С. Решение подходит для компаний, которым нужен надежный и масштабируемый сайт с возможностью расширения функционала через модули и интеграции.

Permalink

Нужны подписчики в Telegram? Поможем быстро увеличить аудиторию вашего канала или группы. Переходите по запросу настоящие подписчики в телеграмм канал. Предлагаем накрутку живых и активных подписчиков без резких скачков и с минимальными списаниями. Подходит для старта новых каналов, повышения доверия и привлечения органической аудитории. Безопасное продвижение, гибкие объемы заказа и быстрый запуск. Увеличьте популярность вашего Telegram-канала уже сегодня.

Permalink

Самые актуальный новости актуальные новости — свежие события, аналитика и репортажи. Политика, экономика, технологии и общество. Будьте в курсе последних новостей и ключевых событий каждый день.

Permalink

Промокоды Пятёрочки https://www.time-samara.ru/content/view/785106/transformaciya-sistemy-l… актуальные купоны и скидки на продукты и доставку. Получайте бонусы, снижайте стоимость заказов и экономьте на покупках. Только проверенные промокоды для выгодных покупок в Пятёрочке.

Add new comment