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

????? ???? ????? ??? ?????? ??? ???? ??????? ???? ????. ??? ????? ?? ???? ????? ????? ???? ??????? ?????? ????. ??????? ??? ???? ????????? ??? ??????.

?? ????? ??????? - ?? ?????? ????: ??? ??????? ?????? ?? ???? ?????? ??????? ??? ???? ???? ????? ??????? ?????? ?? ???? ????. ??? ???? ??? ???? ?????? ??? ??????? ??????? ???? ??????? ??????. ????? ?????? ?? ???? ??????? ??????? ??? [url=https://astrologyprediction.org]888starz تحميل[/url] ??? ???? ?? ??????? ???????? ??? ????.

?????? ???? ??? ????? ???? ??????? ?????? ???? ?? ??????? ?????? ?????? ?????????? ????? ???????. ??? ???? ??? ???? ?????? ?????????. ????? ????? ????????? ?????? ?????? ??????? ?? ???????? ??????. ???????? ??? ??????? ??????? ???? ?? ????? ?????? ?? ????????? ?????????.

?? ????? ?????: ???? ???????? ???????????? ???????? ??????? ???????. ????? ????? ????? ??? ??? ?? ????? ??? ???. ???? ????? ????? ????? ??? ??? ??? ?? ??? ?????. ?????? ???? ??????? ????.

????? ????? ???? ???????? ?????? ?????? ???? ??????? ??? ????? ??????? ???. ????? ??????? ????? ??? ??????? ???? ???? ????? ???? ?????. ???? ????? ????????? ?????? ????? ?????.

Permalink

Seguo Crazy Time da parecchi mesi ormai, quindi ho abbastanza sessioni alle spalle. All'inizio usavo solo il browser, poi sono passato all'applicazione e non torno indietro. Il video parte prima, le puntate si piazzano senza quel ritardo fastidioso.

Se non ci avete mai giocato, parliamo del format live piu' famoso di Evolution, con la ruota principale e quattro bonus: Cash Hunt, Pachinko, Coin Flip e il Crazy Time vero e proprio. L'RTP dichiarato gira intorno al 96 per cento, con differenze sensibili tra numeri e bonus. Si entra anche con dieci centesimi, quindi il banco di prova costa pochissimo.

Sul download bisogna chiarire una cosa: su Android l'installazione e' manuale con il file apk, visto che le regole dello store bloccano parte di queste app. Su iPhone basta salvare il sito sulla schermata principale, e all'atto pratico e' lo stesso. La guida all'installazione e il file corretto si trovano su [url=https://bnbpi.com]crazy time app[/url] conviene prendere il pacchetto da li' e non da forum a caso.

La diretta non divora giga come temevo, anche se con rete debole si vede. Con poca copertura la diretta cala di definizione, ma le puntate continuano a registrarsi. Ho provato con due telefoni diversi, su entrambi nessun crash in sei mesi. Pesa pochi decine di mega.

Sul ritiro delle vincite nessun problema: e-wallet in giornata, bonifico piu' lento. Il KYC meglio sbrigarlo al momento dell'iscrizione, cosi' non ci sono attese al primo prelievo. La chat e' in italiano senza attese assurde. Nel complesso, giocato con testa e con puntate piccole, e' il formato piu' divertente del live.

Permalink

Konto zalozylem na poczatku roku, wiec to nie jest opinia po jednym wieczorze. Interesowal mnie przede wszystkim program lojalnosciowy, bo na start sypia kasa, a pozniej zapominaja o graczu. Na tej stronie jest z tym lepiej - cotygodniowy cashback leci regularnie, w moim przypadku bylo to kilka procent.

Biblioteka automatow jest naprawde obszerny, chociaz wracam do tych samych kilku. Dostawcami sa Pragmatic Play, Play'n GO, Nolimit City oraz Yggdrasil, wiec standardowa czolowka. Za stoly odpowiada Evolution, wiec teleturnieje, ruletka i blackjack. Polskojezyczni krupierzy bywaja, ale nie o kazdej porze dnia.

Oferta dla nowych to 100% do 2000 zl i 150 darmowych spinow, z warunkiem obrotu czterdziestokrotnym, co jest do przerobienia przy spokojnej grze. Aktualne kody promocyjne i to co akurat leci sprawdzisz na [url=https://brylantini.pl]fieryplay[/url] przed pierwszym depozytem. Warto tez zerknac na turnieje, czasem gra sie o naprawde sensowna kase.

Prog wplaty wynosi okolo 40 zl, place Blikiem, bo najszybciej, jest tez Visa, Mastercard i kryptowaluty. Pieniadze na Skrillu mialem nastepnego dnia, na karte potrafi ciagnac sie dwie doby. KYC przeszedlem przy drugim podejsciu, bo pierwszy skan byl nieczytelny, dalej szlo gladko.

Z komorki korzystam bez aplikacji i spokojnie wystarcza. Chodzi plynnie, choc stoly na zywo wymagaja dobrego internetu. Czat obsluguje jezyk polski i nie jest to translator, czekalem srednio kilka minut. Licencja Curacao wiec tak jak cala reszta rynku. Grunt, ze kasa wraca bez cyrku.

Permalink

Ссылка https://npprteamshop.com/google/akkaunty-google-ads/ ведёт в раздел, где рекламные аккаунты разложены по типу доступа, возрасту и стране регистрации, что заметно ускоряет подбор под конкретную связку. Каждая позиция сопровождается описанием: есть ли привязанная карта, какой платёжный порог установлен, сколько дней профилю и какой почтовый ящик идёт в комплекте. В NPPRTEAMSHOP валидность проверяют перед отправкой, а спорные случаи разбирают индивидуально, не отправляя покупателя ждать неделями.

Permalink

Testing a new offer usually means burning a few cabinets, so keeping a small reserve from https://npprteamshop.com/en/google/google-ads-accounts/ saves days of downtime between launches. The catalog separates freshly registered profiles from aged ones with billing history, letting you spend less on throwaway tests and more on the cabinets meant to scale. Communication with npprteamshop.com stays direct, so questions about geo availability or bulk pricing get answered before you commit.

Permalink

Agencies that write to clients from a shared brand identity benefit from Proton Mail accounts with custom domain, since alias creation under one paid mailbox replaces a pile of separate registrations. Listings on npprteamshop.com describe the subscription tier, the registration date and the recovery option attached to each account, so nothing has to be assumed. Bulk requests are quoted through direct contact, and the guarantee terms apply equally to single units and to larger sets.

Permalink

Гео регистрации напрямую влияет на доверие площадки, поэтому под трафик из Штатов правильнее сразу взять безлимитный БМ USA, а не переучивать европейский ресурс. Ассортимент npprteamshop.com включает варианты разного возраста с пройденным ЗРД, привязанной почтой и настроенной двухфакторной аутентификацией, детали указаны в описании позиции. При закупке объёма менеджер поможет распределить кабинеты по связкам и согласует условия подмены проблемных единиц.

Permalink

Inventory planning gets simpler when you buy google accounts that already carry phone confirmation, a matching recovery mailbox and a few weeks of natural activity behind them. NPPR Team Shop lists each batch by registration age, country of creation and whether cookies and 2FA backup codes ship with the login data. Bulk requests are answered by support within the same working day, and dead logins are swapped under the stated replacement window.

Permalink

Если задача в том, чтобы профиль выдержал серию публикаций со ссылками, стоит смотреть на аккаунты Twitter с подтвержденным номером и историей активности, а не на пустые регистрации без подтверждений. Каталог NPPRTeamShop разделён по признакам верификации, стране и наличию 2FA, что позволяет собрать нужную связку под конкретную вертикаль. Поддержка отвечает в мессенджере и разбирает спорные ситуации по логам выдачи, включая случаи, когда доступ запрашивался с нового устройства.

Permalink

Badge-heavy channels attract more scrutiny than people expect, and that is where verified Twitch accounts for sale from NPPR Team save hours of manual confirmation work. Each card explains the email type, whether phone confirmation was completed, the country used at registration and how the profile was gently warmed with follows and chat presence. Data arrives as a clean pack with cookies and recovery details, returns apply to non-working logins, and repeat volume orders get negotiated pricing.

Permalink

Отдел закупок агентства обычно ищет не разовую партию, а стабильный источник, и такой источник представлен на странице https://npprteamshop.com/email-accounts/ с регулярным пополнением стока. В наличии почта под регистрацию рекламных кабинетов, под прогрев аккаунтов соцсетей и под технические нужды вроде привязки платёжных сервисов, с указанием, какие данные входят в комплект. NPPR Team Shop даёт возможность договориться о повторяющихся поставках, чтобы не собирать объём вручную каждый раз перед запуском.

Permalink

Media teams that lose ad accounts to email verification loops usually need gmail accounts with recovery email rather than bare logins with no fallback. The delivery file from NPPRTeamShop lists the mailbox password, the recovery address with its own credentials and the registration geo, which makes handing assets to a colleague simple. Orders of a hundred or more are prepared on request, and the shop keeps the same format across large drops so your internal sheet stays consistent.

Permalink

Anyone tired of soap-style registrations can browse https://npprteamshop.com/en/google/gmail-accounts/ and sort inventory by creation date, verification type and proxy region used during signup. What makes NPPRTeamShop practical is the warm-up applied to older mailboxes, which have real activity in the inbox before they reach the buyer. Delivery is automatic after checkout, and the support desk reviews replacement requests for accounts that lock during the first login attempt.

Permalink

Стабильная работа регистрационного потока начинается с нормальной почты, поэтому арбитражники предпочитают купить аккаунт Yahoo сразу пачкой под конкретное гео. Ассортимент NPPRTeamShop включает как только что созданные ящики, так и отлежавшиеся несколько месяцев, что важно для связок с длинным циклом жизни. Крупные объёмы согласуются через поддержку, там же уточняют доступные страны и сроки подготовки партии.

Add new comment