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

Been using Rolletto Casino for about five months now, so the initial novelty has worn off. Came across it while comparing promo codes, since I wanted somewhere that combines casino and sports without fuss. The game library here covers a lot of ground, though I personally stick to maybe twenty titles.

The software side is well covered: Pragmatic Play, NetEnt, Play'n GO, Hacksaw and Red Tiger. Book of Dead and Reactoonz sit near the top, but the Megaways section is what keeps me coming back. Live casino runs through Evolution, meaning the standard roulette, blackjack and baccarat tables plus the wheel games. Betting on football and tennis is another option, a nice extra for those who like to mix it up.

The starting promotion at Rolletto covers the first four deposits: deposit bonuses that stack up to a decent total. The rollover sits at 40x, standard for a crypto-friendly casino. The live codes for this month can be checked on [url=https://daggymanmusic.com]rolletto[/url] since terms change regularly. Weekly cashback and tournament entries pop up regularly, which keeps things interesting after the first deposit.

You can start from as little as ten euros. Card payments work, although the crypto options are the quickest route: a dozen different coins. Crypto cashouts came through within hours, fiat payouts were slower as expected. Verification was painless — the whole thing was over in twenty-four hours.

I play on the phone via the site and load times are quick. You do not need to download anything, which honestly I prefer. Live chat replies within a few minutes and they are more helpful than most. Regulation is Curacao based, which is worth knowing before you sign up. What matters is the money arrives when you ask for it.

Permalink

Been playing at Revery Play Casino for a few months now, so the first impression stage is well past. A mate at work mentioned it, mainly because the bonus terms elsewhere were ridiculous. The game selection here is decent, with a good mix of slots, table games and live dealer.

Software comes from Pragmatic Play, NetEnt, Play'n GO, Nolimit City and Hacksaw Gaming. Book of Dead and Reactoonz are easy to find, but I gravitate toward the high volatility section. Live casino is Evolution, so Lightning Roulette, Crazy Time, blackjack and baccarat. English speaking dealers around the clock, but low stake tables get busy in the evening.

The welcome bonus here offers a matched deposit plus spins. The playthrough sits at 35x, which is reasonable for a UK facing site. Active bonus terms can be checked on [url=https://www.shreysports.com/sa/reveryplay-account-verification-guide-fo… play[/url] since these change monthly. Cashback and free spin drops appear regularly.

Minimum deposit is ten pounds. Visa, Mastercard, PayPal and Paysafecard go through smoothly. PayPal payouts arrived quickly, bank transfers ran a couple of days. Document check was straightforward — driving licence and a utility bill, cleared in a few hours.

I use the mobile site on my phone and performance is smooth. No app needed, which I prefer anyway. The chat team replies within minutes and wait times are short. Licence is Curacao, so not UKGC, which is worth knowing. The main thing is withdrawals have been honoured.

Permalink

Если вы планируете подобрать нанять телохранителя в москве для сопровождения. Сотрудники безопасности осуществляют контроль безопасности мероприятия. Для организации сопровождения важно проверить формат сопровождения. Нужна охрана? Закажите консультацию и обсудите подходящий формат охраны.

Permalink

Найдите удобное рейтинг лучших казино с учетом условий сервиса. Выберите из игровым столам и начните игровой сеанс. В игровом разделе вас ждут разные игровые категории. Готовы начать? Выбирайте подходящую игру. Перед регистрацией проверьте правила, возрастные требования и доступность сервиса в вашем регионе. Играйте ответственно.

Permalink

mexican pharmacy order online or does mexico sell prescription drugs best mexican online pharmacy
http://www.xjjgsc.com/Redirect.aspx?url=https://solmedsdirect.com mexico pharmacy order online delivery and http://www.orangepi.org/orangepibbsen/home.php?mod=space&uid=7037091 mexican pharmacy that ships to the us
best mexican pharmacy for prescriptions mexico pharmacy order online prescription and online pharmacies in mexico mexico pharmacy mail order online

Permalink

Буду знать, большое спасибо за информацию.
Рецензии о SEO играют ключевую роль в формировании репутации бизнесов. SEO отзывы, [url=https://t.me/seoetc/862]https://t.me/seoetc/862[/url] помогают будущим клиентам выработать обоснованный выбор. Честные оценки услуг способствуют доверительному восприятию. Как ни странно, SEO отзывы — это основной фактор, определяющий успех бизнеса в цифровом пространстве.

Add new comment