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

Anyone shortlisting google ads agency should ask who performs the work, how often results are reviewed, and what reporting is included. For lead generation, the agency should discuss lead quality, offline conversion imports, sales feedback, and wasted-search-term control. The best partner is usually the one that explains tradeoffs clearly and leaves the advertiser in control of its data.

Permalink

A practical shortlist of best international dating sites should compare profile quality, messaging rules, mobile access, identity checks, and how recommendations are generated. A credible comparison should note message limits, profile visibility, refund policies, automatic renewal, and whether essential controls require payment. Clear comparisons help readers avoid hidden restrictions and choose a service that matches their actual dating priorities.

Permalink

Anyone researching buy tiktok likes should compare recent reviews, delivery terms, refund rules, privacy practices, and the risks attached to artificial engagement. Purchased metrics cannot replace strong content, audience research, consistent posting, and genuine interaction with viewers. A cautious comparison protects the account owner from sharing sensitive information or purchasing a package that does not match the goal.

Permalink

Подбирайте щетки для ремонта и обслуживания оборудования. В ассортименте доступны запасные комплектующие. Перед покупкой проверьте тип материала и конструкцию контактов. Подбирайте комплектующие по характеристикам для своевременной замены изношенных элементов.

Permalink

When assessing google ads agency, prioritize measurable business outcomes, clear responsibilities, realistic timelines, and unrestricted access to campaign data. The contract should state ownership of campaigns, creative assets, audiences, conversion actions, dashboards, and historical account data. The best partner is usually the one that explains tradeoffs clearly and leaves the advertiser in control of its data.

Permalink

Anyone comparing options for buy tiktok likes should read both positive and negative reviews, paying attention to dates, order sizes, and complaint resolution. Large packages can create unusual engagement patterns, making gradual delivery and realistic expectations more relevant than headline quantity. That checklist helps distinguish a documented service process from marketing language designed only to encourage a quick purchase.

Permalink

what does gabapentin 100 mg do and gabapentin 800 mg phenibut vs gabapentin
https://www.domainsherpa.com/share.php?site=http://neuroreliefdirect.com how long does it take for gabapentin to relieve anxiety or http://ussher.org.uk/user/mtniygwgpc/?um_action=edit can gabapentin increase nerve pain
gabapentin 300 mg uses side effect gabapentin causing myoclonus or can gabapentin be used for menopause can gabapentin be used for menopause

Permalink

Получите информацию о в рамках анализа кракен даркнет с учетом вопросов безопасности и законодательства. Аналитические публикации рассматривают правовые аспекты использования подобных ресурсов.

Permalink

стоимость поверки теплосчетчика поверка теплосчетчиков многоквартирного дома

Permalink

Mostly a reader, rarely post, but I figured I would share how I pick an online casino these days. After trying maybe a dozen sites I stopped going by ads alone.

Licence comes first for me: see which authority is listed in the footer, and whether they actually accept players from your country. Next come deposits and withdrawals: card, e-wallets and bank transfer should all be there, and there should be no weird fees on cashouts.

The welcome offer is where most people get caught. Anything above 40x rollover is a red flag for me, and live tables often do not count at all. A good recent review that covers all of this is worth a read here [url=https://sites.google.com/view/superbet-casino-7446/]Superbet ervaringen[/url] and it saved me some time.

Most of my sessions are on mobile, and if there is an app I make sure it comes from the official page. Ask support one simple question first: slow or scripted answers usually mean trouble later.

Anyway, that is my routine. Set a budget and stick to it.

Permalink

rybelsus bioavailability or rybelsus dose equivalent to ozempic what happens when you stop taking rybelsus
https://maps.google.dm/url?sa=t&url=https://semaoraldirect.com can you take more than 14 mg of rybelsusand https://mantiseye.com/community/yofxfqvsop semaglutide storage
buy rybelsus online how to give semaglutide injection with syringeor does semaglutide help with inflammation get semaglutide

Permalink

Add new comment