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:
- A working Drupal 10 or 9 website.
- Basic knowledge of Drupal site building and module development.
- 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:
- In your Drupal installation, navigate to the sites/all/modules directory (or your preferred module location).
- Create a new directory for your custom module. Give it a unique and descriptive name, such as my_custom_content_type.
- 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:
- nodeThis 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.
- Create a file named my_custom_content_type.module in your module directory.
- 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.
- 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
- In your Drupal admin interface, navigate to Extend (admin/modules) and enable your custom module, "My Custom Content Type Module."
- 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.
Comment
http://isocleardirect.com/#…
http://isocleardirect.com/# purchase isotretinoin pills
order synthroid overnight…
order synthroid overnight ThyroWellRx synthroid cost without insurance
https://dutashielddirect…
https://dutashielddirect.shop/# can i buy generic avodart
where can i buy avodart for…
where can i buy avodart for sale: dutashielddirect - where can i buy avodart without a prescription
https://isocleardirect.shop/…
https://isocleardirect.shop/# order accutane overnight delivery
buy generic avodart:…
buy generic avodart: DutaShield Direct - can i order cheap avodart no prescription
zithromax 250 mg tablet…
zithromax 250 mg tablet price or zithromax z-pak zithromax cost canada
https://www.google.co.uz/url?q=https://rapidzithrodirect.com zithromax antibiotic without prescription and https://www.liveviolet.net/user/qblaceiapx/videos zithromax antibiotic without prescription
can you buy zithromax online zithromax 500 mg lowest price drugstore online or buy zithromax 1000mg online zithromax drug
https://isocleardirect.com/#…
https://isocleardirect.com/# where to buy accutane online safely
zithromax 250 mg tablet…
zithromax 250 mg tablet price rapidzithrodirect zithromax over the counter
https://cardiostatindirect…
https://cardiostatindirect.com/# atorvastatin 80mg prescription free
buy cystic acne medication…
buy cystic acne medication accutane: IsoClear Direct - accutane price per pill
can i purchase generic…
can i purchase generic avodart and can you buy generic avodart tablets buying avodart
http://maps.google.cz/url?q=https://dutashielddirect.com cost generic avodart without rx and https://act2day.eu/profile/fkduerbomy/ can i purchase generic avodart online
how can i get avodart without dr prescription can i purchase generic avodart for sale or can you get avodart without rx cheap avodart pill
zithromax z-pak price…
zithromax z-pak price without insurance and zithromax antibiotic without prescription purchase zithromax z-pak
https://nxu.biz/smart_intelligence_engine/?q=http://rapidzithrodirect.c… zithromax 500mg price and https://www.liveviolet.net/user/tpnkbxbjdz/videos buy zithromax online with mastercard
can i buy zithromax online zithromax tablets for sale or zithromax generic cost zithromax azithromycin
http://cardiostatindirect…
http://cardiostatindirect.com/# generic lipitor 40mg cost
zithromax without…
zithromax without prescription: rapidzithrodirect - purchase zithromax z-pak
buy synthroid 125 mcg…
buy synthroid 125 mcg thyrowellrx where to buy levothyroxine online
https://isocleardirect.shop/…
https://isocleardirect.shop/# buy accutane discreet shipping
Пройти обязательную…
Пройти обязательную роспромтест отказное письмо можно для подтверждения соответствия продукции. Специалисты сопроводят оформление. В зависимости от продукции определяется необходимый комплект документов.
Выберите профессиональный…
Выберите профессиональный роспромтест при подготовке разрешительной документации. Эксперты помогут определить требования. Для разных видов продукции выбирается необходимый формат оценки.
Оформите опытный роспромтест…
Оформите опытный роспромтест для решения задач по оценке товаров. В центре помогут определить необходимые документы. С учетом назначения товара уточняются требования.
Обратитесь в опытный …
Обратитесь в опытный роспромтест для подготовки разрешительной документации. Сотрудники помогут разобраться в требованиях. После анализа характеристик подбирается подходящая схема.
Закажите необходимый…
Закажите необходимый стоимость сертификата исо 9001 для подтверждения соответствия системы менеджмента качества. Эксперты помогут подготовить документы. С учетом особенностей организации выбирается подходящая процедура.
can you buy generic avodart…
can you buy generic avodart no prescription or cost of cheap avodart without a prescription can i purchase avodart without dr prescription
http://www.wzdq123.com/go.php?url=http://dutashielddirect.com how can i get avodart without rx and https://act2day.eu/profile/mmmbelkyye/ how to get generic avodart without rx
cost cheap avodart without prescription can you get avodart price or can i buy cheap avodart for sale where to buy cheap avodart without a prescription
Сварочные технологии https:/…
Сварочные технологии https://svarkahub.ru требуют не только практических навыков, но и понимания особенностей материалов, режимов сварки, конструкции соединений и требований нормативных документов. На специализированных ресурсах можно найти информацию по ручной дуговой и полуавтоматической сварке, сварочным материалам, оборудованию, ГОСТ и различным инженерным расчетам. Полезными бывают также справочные материалы для сварщиков, технологов и специалистов производства, позволяющие быстрее разобраться с конкретной производственной задачей. Подробные материалы по сварке, нормативным требованиям и расчетным инструментам собраны на сайте SvarkaHub.
Открой для себя Лугаленд…
Открой для себя Лугаленд https://lugaland.com — портал самых интересных новостей, фактов и полезных обзоров. Наслаждайся увлекательными историями, познавательными тестами, забавными видео и улётными подборками шуток и мемов. Лугаленд — твой ключ к знаниям, позитиву и нескучному досугу!
Architectural Barn Door Kits…
Architectural Barn Door Kits - Statement sliding doors featuring exposed matte black hardware or concealed magic-track sliding systems: https://www.designerdoorssupply.com/catalog/barn
https://cardiostatindirect…
https://cardiostatindirect.com/# lipitor 20mg price per pill
zithromax purchase online…
zithromax purchase online and zithromax prescription zithromax 500 price
http://www.meetthegreens.org/cgi-registry/bridgepop.pl?url=rapidzithrod… zithromax 1000 mg online and https://www.0468wudi.com/home.php?mod=space&uid=304457 generic zithromax over the counter
zithromax price south africa buy zithromax online and zithromax for sale cheap zithromax for sale us
Собираетесь быстро где…
Собираетесь быстро где купить саженцы деревьев для участка. В специализированных магазинах представлены декоративные культуры. При выборе сравните возраст растения. Для разных участков легко выбрать саженцы для конкретных условий.
п»їbuy synthroid online and…
п»їbuy synthroid online and buy levothyroxine online pharmacy cheap synthroid 90 day supply
https://images.google.tk/url?sa=t&url=https://thyrowellrx.com п»їbuy synthroid onlineand http://lenhong.fr/user/buzlndwvry/ generic synthroid for sale
order levothyroxine without prescription buy thyroid hormone pills onlineand synthroid 200 mcg price per pill cheap synthroid 90 day supply
Those who enjoy manga may…
Those who enjoy manga may manga while exploring favorite stories. The collection contains romance, so manga enthusiasts can choose a suitable story. Series updates allow fans to keep up with favorite series
http://dutashielddirect.com/…
http://dutashielddirect.com/# can i purchase avodart price
Fresh publication here…
Fresh publication here company formation in montenegro step by step
Key information inside www…
Key information inside www.montenegro-company-registration.com/
Explore the complete post…
Explore the complete post montenegro-company-registration.com
A collection worth exploring…
A collection worth exploring official website
Check today's publications…
Check today's publications open company in montenegro
Find today's top stories…
Find today's top stories click here
Skip to details company…
Skip to details company formation montenegro
View the complete report…
View the complete report this site
order levothyroxine 175 mcg…
order levothyroxine 175 mcg ThyroWellRx order levothyroxine 175 mcg
Fans Japanese comics can…
Fans Japanese comics can easily manga reading website to explore favorite stories. The collection contains romance, meaning that visitors can discover a favorite genre. Latest episodes allow fans to keep up with favorite series
Readers Japanese comics and…
Readers Japanese comics and series can where to read manga for free to explore interesting series. Available titles contains fantasy, so every reader can pick a favorite genre. Latest episodes help readers continue reading
https://isocleardirect.com/#…
https://isocleardirect.com/# isotretinoin online prescription free
http://cardiostatindirect…
http://cardiostatindirect.com/# buy lipitor from canadian pharmacy
cheap isotretinoin 10mg:…
cheap isotretinoin 10mg: IsoClear - buy accutane from canada
Manga fans Japanese comics…
Manga fans Japanese comics may unblocked manga websites to find interesting series. Available titles includes romance, meaning that manga enthusiasts can pick an interesting title. New chapters allow fans to continue reading
Enthusiasts Japanese comics…
Enthusiasts Japanese comics and series may manhwa read to find popular works. The selection contains adventure, so every reader can discover a new series. Fresh releases help readers keep up with favorite series
Readers graphic stories can…
Readers graphic stories can easily manga reading website to explore fresh chapters. Available titles contains comedy, so every reader can pick an interesting title. Latest episodes allow fans to discover what happens next
Fans graphic stories can…
Fans graphic stories can conveniently read manga online free to find popular works. The selection contains drama, allowing every reader can find a suitable story. Series updates help readers continue reading
Pagination
Add new comment