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

Медиабаинг в соцсетях требует запаса профилей, и аккаунты Instagram для арбитража трафика лучше брать пачкой, а не поштучно перед самым стартом. В каталоге NPPR TEAM SHOP описаны срок регистрации, тип подтверждения, наличие фото и постов, а также формат передачи доступов с токеном и почтой. Замену по невалиду оформляют сразу после проверки, поэтому потери на старте связки остаются в пределах допустимого.

Permalink

Sorting good inventory from recycled junk takes time, so the ordering flow on https://npprteamshop.com/en/facebook/fan-pages/ shows page age, publication frequency and whether the asset has ever carried advertising before you commit. Listings maintained by npprteamshop.com cover United States, United Kingdom, German and Polish origins, with organic follower bases rather than obvious bot spikes that reviewers flag instantly. Access packets include the owning profile, its mail box and 2FA source, and anything that cannot be transferred correctly is exchanged under the published terms.

Permalink

Тем, у кого кабинет ушёл в блок посреди пролива, нужен быстрый ресурс, и здесь выручает возможность купить аккаунт Яндекс с российским IP регистрации и готовой привязкой SIM. Каталог npprteamshop.com разделён по возрасту профиля и наличию активности, поэтому под прогрев берут одно, а под моментальный старт совсем другое. Доставка данных занимает минуты, при технической проблеме ресурс меняют по регламенту сервиса.

Permalink

Filled friend lists change how a profile is read by moderation, which is why Facebook accounts with friends tend to survive the first ad submission better than blank registrations. Listings at NPPR TEAM SHOP state the friend count, registration period and whether the profile carries photos, timeline activity and group memberships, so you can match the asset to the offer instead of guessing. Delivery arrives as a package with login, password, linked mail access and cookies, and replacements cover profiles that fail on first entry.|

Permalink

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

Permalink

Anyone comparing catalogs before a messaging push should look at https://npprteamshop.com/en/discord/ where stock is sorted by age, verification and available access format. NPPR Team keeps mail credentials, cookies and 2FA data in one archive per order, which shortens onboarding when a team splits profiles across several operators. Bulk buyers can request a reserved batch, and warranty claims are processed under the conditions printed next to every item.

Permalink

Разница в конверсии между локальным и случайным гео заметна уже на первых инвайтах, поэтому есть смысл купить аккаунты Discord USA под конкретную воронку. У NPPR TEAM SHOP профили выдерживаются перед продажей, привязываются к рабочему ящику и передаются вместе с токеном для подключения к автоматике. Замена оформляется через тикет, а вопросы по совместимости с прокси разбирают в переписке без формальных отписок.

Permalink

Server admins check join history before granting roles, and that is exactly where verified discord accounts from NPPR Team Shop behave differently from throwaway registrations. Every profile ships with confirmed email, completed phone step, and an avatar plus bio already filled in, so it reads as a normal member rather than an empty shell. Delivery is automatic after checkout, and the warranty covers accounts that fail to log in on first attempt.

Permalink

Тестирование десятка креативов одновременно требует запаса профилей, и аккаунты Instagram для арбитража трафика покрывают эту потребность без простоев. Внутри каталога NPPRTeamShop есть позиции разной выдержки — от двухнедельных до годовалых, с подтверждением по SMS и полным пакетом доступов, включая cookies и токен. Каждая партия проверяется перед отгрузкой, поэтому байер получает рабочий материал, а не список из мёртвых логинов.

Permalink

Media buyers who need spend to start on day one usually pick a tiktok ads account with balance instead of waiting on a card review cycle. NPPR TEAM SHOP hands over the cabinet with the funded amount visible inside, full email access, 2FA codes and the cookie set required for a clean first login from your proxy. Replacement is handled if the balance is unusable on arrival, and bulk requests for five or more cabinets are prepared by the support desk in advance.

Permalink

Прогретые ящики с историей входов и реальной активностью в почтовом клиенте дают совсем другую доставляемость, и gmail аккаунты для рассылки в каталоге подобраны именно под такую задачу. Магазин npprteamshop.com отмечает возраст регистрации, включён ли IMAP и какие данные входят в комплект, включая токен восстановления. Перед стартом отправок рекомендуется первые сутки держать умеренный темп, а при обнаружении блока на стороне Google оформить обращение на замену.

Add new comment