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:
- A working Drupal 10 or 9 website.
- Basic knowledge of Drupal site building and module development.
- 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:
- In your Drupal installation, navigate to the sites/all/modules directory (or your preferred module location).
- Create a new directory for your custom module. Give it a unique and descriptive name, such as my_custom_content_type.
- 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:
- nodeThis 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.
- Create a file named my_custom_content_type.module in your module directory.
- 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.
- 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
- In your Drupal admin interface, navigate to Extend (admin/modules) and enable your custom module, "My Custom Content Type Module."
- 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.
Comment
Ремонт грузовых автомобилей…
Ремонт грузовых автомобилей https://minskdiesel.by в Минске? Сервис «Дизель Практик» вернёт технику в строй в кратчайшие сроки! Срочный ремонт, выездная диагностика, запчасти в наличии. Доверьтесь профессионалам с многолетним опытом — надёжность и прозрачность на каждом этапе.
вызов нарколога на дом запой…
вызов нарколога на дом запой срочный вызов нарколога
Ремонт грузовых автомобилей…
Ремонт грузовых автомобилей https://minskdiesel.by в Минске? Сервис «Дизель Практик» вернёт технику в строй в кратчайшие сроки! Срочный ремонт, выездная диагностика, запчасти в наличии. Доверьтесь профессионалам с многолетним опытом — надёжность и прозрачность на каждом этапе.
выезд на дом нарколога…
выезд на дом нарколога анонимно нарколог выезд на дом
Разработка сайтов на 1С…
Разработка сайтов на 1С-Битрикс — надежное решение для бизнеса любого масштаба. Переходите по запросу разработка сайтов на Битрикс. Создаем корпоративные сайты, интернет-магазины и порталы с удобным управлением, высокой производительностью и интеграцией с CRM, 1С и другими сервисами. Выполняем полный цикл работ: от проектирования и дизайна до запуска и технической поддержки. Разрабатываем современные сайты, которые помогают привлекать клиентов и увеличивать продажи.
вызов врача нарколога на дом…
вызов врача нарколога на дом недорого вызов нарколога на дом цены
вызов врача на дом нарколога…
вызов врача на дом нарколога нарколог на дом цена
нарколог анонимно анонимная…
нарколог анонимно анонимная наркологическая нарколог на дом анонимно
вызов врача на дом нарколога…
вызов врача на дом нарколога нарколог на дом анонимно
выезд врача нарколога на дом…
выезд врача нарколога на дом нарколог на дом цена
нарколог на дому капельниц…
нарколог на дому капельниц врач нарколог на дом
прием нарколога нарколог…
прием нарколога нарколог наркологическая помощь
The 2025/26 Premier League…
The 2025/26 Premier League premier-league-tabella.hu table, featuring the current standings, points totals, and match results. Follow the battle for the championship, European places, and league status. Game schedules, statistics, matchday overviews, and the latest season data are available.
The latest NBA https://www…
The latest NBA https://www.nb1-tabella.hu standings with match results, schedule, and the latest basketball news. Learn about team and player achievements, track standings, explore statistics, and get highlights of the season's most exciting games.
NBA standings https://nbi…
NBA standings https://nbi-tabella.hu/ match results, game schedule, and the latest basketball season news. Follow conference standings, player stats, game results, the tournament schedule, and all the important events of the National Basketball Association.
NBA standings https://www…
NBA standings https://www.nbi-tabella.hu match results, game schedule, and the latest basketball season news. Follow conference standings, player stats, game results, the tournament schedule, and all the important events of the National Basketball Association.
The latest NBA nb1-tabella…
The latest NBA nb1-tabella hu standings with match results, schedule, and the latest basketball news. Learn about team and player achievements, track standings, explore statistics, and get highlights of the season's most exciting games.
The 2025/26 Premier League…
The 2025/26 Premier League premier-league-tabella hu table, featuring the current standings, points totals, and match results. Follow the battle for the championship, European places, and league status. Game schedules, statistics, matchday overviews, and the latest season data are available.
NBA news https://nb2-tabella…
NBA news https://nb2-tabella.hu/ game results, schedules, and the latest season standings. Get the latest information on teams, players, and the tournament, analyze statistics, and follow the championship race and playoff progress.
NBA news nb2 tabella game…
NBA news nb2 tabella game results, schedules, and the latest season standings. Get the latest information on teams, players, and the tournament, analyze statistics, and follow the championship race and playoff progress.
The latest Liverpool news…
The latest Liverpool news liverpool-meccs fixtures, and season results. Get up-to-date information on team performances, lineup changes, player achievements, match statistics, and key events in English and European football.
Liverpool's league table…
Liverpool's league table http://www.liverpool-tabella.hu/ shows the team's current standings, points earned, and form. Follow the team's latest match results, win/loss statistics, season dynamics, and the battle for top spots in the standings.
The latest Liverpool news…
The latest Liverpool news https://liverpool-meccs.hu fixtures, and season results. Get up-to-date information on team performances, lineup changes, player achievements, match statistics, and key events in English and European football.
Liverpool's league table…
Liverpool's league table liverpool-tabella shows the team's current standings, points earned, and form. Follow the team's latest match results, win/loss statistics, season dynamics, and the battle for top spots in the standings.
Pagination
Add new comment