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

Speel hier inmiddels een maandje of vijf en wilde toch even mijn kant van het verhaal kwijt, want de meeste stukken die je online vindt over lalabet casino review klinken alsof ze door de marketingafdeling zijn geschreven. Een vriend tipte me en verwachtte er niet zo veel van.

De slotcollectie is gewoon dik in orde — ik gok ergens tussen de 3000 en 4000 titels, al tel ik ze niet natuurlijk. Pragmatic Play is zwaar vertegenwoordigd met Gates of Olympus en Sweet Bonanza, en zelf hang ik meer rond Play'n GO — Book of Dead is en blijft mijn ding. NetEnt, Betsoft en wat Big Time Gaming titels vind je er ook, dus er valt genoeg te proberen.

De live-hoek draait op Evolution en dat scheelt echt — geen gehaper bij mij, de dealers zijn gezellig genoeg, en dan heb je Crazy Time nog waar het altijd druk is. Ik verlies daar meer dan me lief is. Wie de actuele voorwaarden wil checken kan even kijken op [url=https://lala-nederland.bet/ervaringen/]lalabet review[/url] voor je een account maakt, die veranderen namelijk regelmatig.

De welkomstbonus was bij mij 100% tot 500 euro plus 200 free spins, inzetvereiste 35x — standaard dus, niks bijzonders. Je kunt al vanaf €10 storten, het account aanmaken duurde niks. Waar ik wel positief van verraste was de verificatie: paspoort geupload en binnen een dag goedgekeurd. Ik heb het bij andere tenten weken zien duren.

Uitbetalen doe ik meestal via Skrill en dat duurt zelden langer dan een etmaal. Visa en Mastercard werken ook, alleen is dat trager, reken op een paar dagen. Crypto kan ook, ik heb een keer met Bitcoin getest en dat was de snelste van allemaal. Wat me echt tegenviel: support liet me een keer twintig minuten wachten, en het eerste antwoord kwam in het Engels binnen. Ze losten het op, maar het duurde.

Mobiel gaat via de browser, geen app nodig en dat is bij mij op iPhone prima. Voor Nederlandse spelers is de licentiekwestie natuurlijk het gesprek — Curacao dus, niet Kansspelautoriteit, dus weet waar je aan begint. Bij mij zijn alle uitbetalingen binnengekomen, dat is mijn ervaring, verder claim ik niks.

Permalink

Is an insurance broker in New York City https://www.ayroyal.com – independent insurance coverage for business and personal needs. As an insurance broker, we compare offers from leading insurance companies and offer you competitive prices with real coverage. Transparency guaranteed!

Permalink

Пройдите комплексное лечение https://medprime-clinic.ru и диагностику в медицинском центре. Полный спектр обследований, консультации профильных специалистов, современные методы лечения, контроль состояния здоровья и индивидуальный подход на всех этапах медицинской помощи.

Permalink

Klikam tu od jakichs czterech miesiecy i szczerze mowiac zarejestrowalem sie bo kolega z pracy marudzil. Przedtem krecilem sie po innych kasynach i glownie chodzilo mi o to, zeby moc obstawiac z telefonu w tramwaju. I akurat tutaj apka daje rade — chodzi plynnie nawet na moim zajechanym Samsungu.

Slotow jest tyle, ze nie ma szans wszystkiego przejsc i to nie sa jakies krzaki. Pragmatic Play jest wszedzie — Sweet Bonanza odpalam chyba najczesciej, choc ostatnio bardziej siedze na Big Time Gaming. Stoly na zywo obsluguje Evolution, dilerzy normalni, zywi ludzie, Lightning Roulette jest tam oczywiscie. Polskojezycznego dilera brak i to troche szkoda.

Bonus powitalny jest w okolicach 100% od pierwszej wplaty plus paczke darmowych spinow, rozbite na kilka dni. Warunek obrotu jest x60, wiec bez cudow — da sie, tylko nie licz na szybkie wyjscie. Aktualne kody i regulamin bonusu mozna podejrzec na [url=https://mostbet-casino-pol.com]mostbet casino aplikacja[/url] zanim sie zarejestrujesz. Najmniejsza wplata zaczyna sie od 20 zl, konto zalozylem w kilkadziesiat sekund, KYC przeszlo mi nastepnego dnia.

Wyplacam najczesciej na Skrill i schodzi to do 2-3 godzin. Na Mastercard trwalo dluzej — dwa dni robocze. Bitcoina i USDT tez przyjmuja, choc sam nie probowalem. To co mnie wkurzylo to ze przy pierwszym cashoucie musialem doslac rachunek za prad — logiczne, tylko po co to na ostatnia chwile.

Czat z konsultantem odpowiada po polsku, w nocy trafilem na anglojezycznego konsultanta. Odpisuja w kilka minut, konkretnie, nie ogolnikami. Dzialaja na licencji Curacao, wiec bez polskiego pozwolenia — kazdy niech sobie sam to przemysli.

Apke sciagalem z ich strony, w Play Store nie uswiadczysz. Wymaga zgody na nieznane zrodla — standard, nic dziwnego. Wersja pod iOS tez jest, kolega ma. Push-e potrafia zasypac, wylaczylem to drugiego dnia.

Permalink

Ask whether the google ads agency works with your existing CRM and can import qualified-lead outcomes.

Permalink

Some gay dating apps focus on swiping. best free gay hookup sites can be better when search filters matter more.

Permalink

Наша лучшая подборка: разработка инструкций по охране труда нормативный документ

Permalink

Самые свежие данные: разработка документов по охране труда для организаций

Add new comment