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

Connect universal payment gateway for igaming for processing transactions. Business solution enables automating payment transactions. When connecting the service available electronic payment methods. Implementation carried out via the API. Before choosing worth evaluating currencies. Request integration cost taking into account the platform features. Submit a request online and get connection information.

Permalink

Организовать помощь https://autsorsing-ohrany-truda-msk.ru для организации. Опытная команда обеспечивают комплекс обязательных мероприятий. В состав услуги проводится оценка профессиональных рисков. Необходимая документация подготавливаются исходя из специфики предприятия. Когда требуется дополнительная помощь ведение направления можно передать внешним специалистам. Такой формат дает возможность систематизировать работу с документами. Ответственному сотруднику можно не вести весь объем документации. Уточните стоимость с учетом специфики бизнеса. Закажите консультацию через сайт и передайте необходимые задачи экспертам.

Permalink

Заказать ведение направления охрана труда аутсорсинг для организации. Профессиональные консультанты обеспечивают текущее сопровождение. В перечень работ входит подготовка инструкций. Рабочие документы подготавливаются с учетом особенностей компании. Когда требуется дополнительная помощь определенный объем работ можно передать внешним специалистам. Привлечение специалистов обеспечивает условия для выстроить рабочие процессы. Работодателю не потребуется тратить рабочее время на рутинные задачи. Рассчитайте условия сотрудничества исходя из задач компании. Оставьте заявку через сайт и выберите подходящий формат сопровождения.

Permalink

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

Permalink

An informative online resource healthfare.ca dedicated to wellness, healthy eating, and a balanced lifestyle. Readers can find informative publications on balanced nutrition, along with practical advice. Visitors can also access information about various products. Among the main topics are balanced daily habits, nutrition and food choices, exercise and fitness, wellness routines, and general wellness.

Permalink

Выбрать услуги услуги по охране труда аутсорсинг для производства. Специалисты компании организуют работу по охране труда. В состав услуги входит подготовка отчетности. Необходимая документация проверяются с учетом особенностей компании. В случае нехватки внутренних ресурсов ведение направления можно полностью делегировать экспертам. Такой формат помогает своевременно проводить необходимые мероприятия. Ответственному сотруднику не потребуется вести весь объем документации. Рассчитайте перечень услуг с учетом количества сотрудников. Отправьте запрос через сайт и получите помощь в ведении охраны труда.

Permalink

The capitalize on of banner, lighting and trivial intermission can completely change how a arcane visual spot is perceived. I originate this article extremely provocative because it examines not too pragmatic draft choices and explains how they induce eager and attention. The chat nearly designing mystery pigment street-light uninterested space provides a productive vantage point on coeval digital aesthetics. Thanks as far as something publishing it.

Add new comment