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
ventolin: AeroBreatheSupply …
ventolin: AeroBreatheSupply - where can i buy ventolin in uk
услуги кейтеринга для…
услуги кейтеринга для банкета кейтеринг сколько стоит
generic zithromax 500mg:…
generic zithromax 500mg: order z-pak online overnight - zithromax 500 price
http://iverbatchdirect.com/#…
http://iverbatchdirect.com/# ivermectin stromectol
buying ventolin online:…
buying ventolin online: ventolin inhaler price online - ventolin best price
http://getzithrosprint.com/#…
http://getzithrosprint.com/# zithromax online usa no prescription
На схеме tditz.ru показано,…
На схеме tditz.ru показано, как воздух проходит поперёк штабеля и возвращается к вентиляторам. По выноскам можно открыть описания отдельных узлов камеры.
Что влияет на расход тепла…
Что влияет на расход тепла https://теплоагрегатный-завод.рф при сушке древесины и когда цеху нужна аспирация? Разберём основные факторы сушки, принципы работы аспирации и ситуации, когда деревообрабатывающему цеху необходима система удаления пыли.
zithromax buy online:…
zithromax buy online: generic zithromax no prescription - zithromax over the counter
Информационный портал https:…
Информационный портал https://robosiri.com предлагает материалы о робототехнике, искусственном интеллекте, автоматизации и технологических разработках. Следите за новостями отрасли, изучайте интересные проекты и знакомьтесь с перспективными решениями.
La Garenne International…
La Garenne International School https://www.la-garenne.ch is an international boarding school in Switzerland, situated in the picturesque Swiss Alps. It offers education for children aged 3 to 18, including the IB curriculum, comfortable boarding facilities, an individualized approach, and a wide range of extracurricular activities.
La Garenne International…
La Garenne International School https://www.la-garenne.ch is an international boarding school in Switzerland, situated in the picturesque Swiss Alps. It offers education for children aged 3 to 18, including the IB curriculum, comfortable boarding facilities, an individualized approach, and a wide range of extracurricular activities.
buy zithromax online cheap:…
buy zithromax online cheap: buy zithromax online - buy zithromax 1000mg online
ivermectin buy nz: Iver…
ivermectin buy nz: Iver Batch Direct - stromectol cost
zithromax cost canada…
zithromax cost canada GetZithroSprint zithromax for sale us
Movie.one — каталог кино…
Movie.one — каталог кино https://movie.one/film с большой коллекцией фильмов и сериалов. Изучайте описания, рейтинги, актёрский состав, интересные факты и находите онлайн-сервисы, где доступны интересующие вас фильмы.
ivermectin nz and buy…
ivermectin nz and buy ivermectin nz can you buy stromectol over the counter
https://www.google.com.uy/url?sa=t&url=https://iverbatchdirect.com where to buy stromectol online or https://exhibitioncourthotel4.co.uk/user-2/fvrpjediez/?um_action=edit cost of ivermectin medicine
ivermectin 50 stromectol medicine and stromectol tab 3mg stromectol 15 mg
ventolin prices: salbutamol…
ventolin prices: salbutamol hfa 100mcg buy - ventolin brand
zithromax online paypal or…
zithromax online paypal or generic zithromax over the counter zithromax 500 mg lowest price online
https://www.domainsherpa.com/share.php?site=http://getzithrosprint.xyz azithromycin zithromaxand https://exhibitioncourthotel4.co.uk/user-2/ekedhavsod/?um_action=edit buy zithromax online
zithromax online paypal buy generic zithromax no prescriptionor buy zithromax 1000 mg online zithromax 500 tablet
Хочешь в ТОП? seo…
Хочешь в ТОП? seo продвижение сайтов продвигаем сайты малого бизнеса, помогая привлекать новых клиентов и делать компанию заметнее в интернете. Подбираем решения с учётом целей, особенностей ниши и бюджета.
Хочешь в ТОП? продвижение…
Хочешь в ТОП? продвижение seo продвигаем сайты малого бизнеса, помогая привлекать новых клиентов и делать компанию заметнее в интернете. Подбираем решения с учётом целей, особенностей ниши и бюджета.
Хочешь в ТОП? поисковое seo…
Хочешь в ТОП? поисковое seo продвижение сайта продвигаем сайты малого бизнеса, помогая привлекать новых клиентов и делать компанию заметнее в интернете. Подбираем решения с учётом целей, особенностей ниши и бюджета.
ivermectin 400 mg brands and…
ivermectin 400 mg brands and ivermectin 8 mg buy stromectol uk
https://www.cirmmt.org/research/projects/researchproject.2011-10-11.500… stromectol tab 3mgand https://mantiseye.com/community/bgzqnnqjkx ivermectin 3 mg tablet dosage
ivermectin 4 ivermectin oralor ivermectin otc stromectol in canada
Если интересует Вечные SEO…
Если интересует Вечные SEO ссылки с Google для продвижения сайта - такие ссылки идеально подходят для роста DR, CF, TF, DA и ИКС, а также для повышения авторитетности домена и поддержки роста позиций. Ссылки размещаются на постоянной основе и могут использоваться для продвижения сайтов разных тематик.
where to get zithromax over…
where to get zithromax over the counter: ZithroSprint - can i buy zithromax over the counter
http://getzithrosprint.com/#…
http://getzithrosprint.com/# zithromax online
Читать статью полностью:…
Читать статью полностью: источник про винтовые сваи
Новое в категории: полезная…
Новое в категории: полезная статья о геологии участка
stromectol otc order generic…
stromectol otc order generic stromectol no rx ivermectin coronavirus
ventolin over the counter…
ventolin over the counter canada and ventolin 90 mcg ventolin 4mg tab
https://images.google.co.th/url?sa=t&url=https://aerobreathesupply.com cost ventolin australia and https://bbsdump.com/home.php?mod=space&uid=73152 ventolin hfa 108
ventolin salbutamol ventolin without prescription or generic ventolin inhaler ventolin mexico
ventolin pharmacy:…
ventolin pharmacy: AeroBreathe - albuterol ventolin
cost of ivermectin pill and…
cost of ivermectin pill and ivermectin usa stromectol 3 mg price
http://www.onlineunitconversion.com/link.php?url=iverbatchdirect.com& stromectol and http://www.1gmoli.com/home.php?mod=space&uid=1385447 ivermectin pill cost
buy liquid ivermectin ivermectin coronavirus or ivermectin 4 buy stromectol
https://aerobreathesupply…
https://aerobreathesupply.xyz/# ventolin 100mcg online
Автоматизация кафе или…
Автоматизация кафе или ресторана электронное меню для ресторана цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
Автоматизация кафе или…
Автоматизация кафе или ресторана системы электронного меню цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
stromectol liquid:…
stromectol liquid: IverBatchDirect - stromectol 15 mg
Автоматизация кафе или…
Автоматизация кафе или ресторана автоматизация ресторана цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
Хочешь в ТОП? seo…
Хочешь в ТОП? seo продвижения продвигаем сайты малого бизнеса, помогая привлекать новых клиентов и делать компанию заметнее в интернете. Подбираем решения с учётом целей, особенностей ниши и бюджета.
Хочешь в ТОП? продвижение…
Хочешь в ТОП? продвижение сайта seo продвигаем сайты малого бизнеса, помогая привлекать новых клиентов и делать компанию заметнее в интернете. Подбираем решения с учётом целей, особенностей ниши и бюджета.
http://iverbatchdirect.com/#…
http://iverbatchdirect.com/# ivermectin uk coronavirus
ventolin canada: Aero…
ventolin canada: Aero Breathe Supply - ventolin inhalers
zithromax 500: buy zithromax…
zithromax 500: buy zithromax online - zithromax azithromycin
https://getzithrosprint.xyz/…
https://getzithrosprint.xyz/# zithromax for sale online
buy zithromax 1000 mg online…
buy zithromax 1000 mg online: ZithroSprint - where to get zithromax over the counter
Автоматизация кафе или…
Автоматизация кафе или ресторана система автоматизации ресторана цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
Автоматизация кафе или…
Автоматизация кафе или ресторана автоматизация ресторана цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
Автоматизация кафе или…
Автоматизация кафе или ресторана https://avtomatizaciya-restorana.ru цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
Автоматизация кафе или…
Автоматизация кафе или ресторана лучшее приложение для доставки еды цифровая экосистема для ресторанов, кафе и служб доставки. Управляйте заказами, клиентской базой, программами лояльности и маркетингом, запускайте собственные каналы продаж и развивайте доставку без зависимости от агрегаторов.
Pagination
Add new comment