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
Napdoku: Cozy Brain Puzzle 猫…
Napdoku: Cozy Brain Puzzle 猫 パズル is a relaxing logic game designed for brain training and unwinding. Solve number puzzles to sharpen your attention, concentration, and logical thinking skills as you progress through increasingly challenging levels.
https://amoxisprintmeds.com/…
https://amoxisprintmeds.com/# cost of amoxicillin 875 mg
buy amoxicillin online…
buy amoxicillin online without prescription: Amoxi Sprint Meds - amoxicillin 30 capsules price
https://corticalmsupply.xyz/…
https://corticalmsupply.xyz/# prednisone 200 mg tablets
SynapseFuel: buy modafinil…
SynapseFuel: buy modafinil online - buy modvigil no prescription
prednisone 10 mg and…
prednisone 10 mg and prednisone purchase online prednisone oral
http://www.xhen-long.com/cms/rfd_01.cgi?id=1&mode=redirect&no=2&ref_eid… prednisone 20 mg genericor http://ussher.org.uk/user/ehiirlypek/?um_action=edit buy prednisone online india
prednisone 54899 prednisone rx couponor buy prednisone mexico where can you buy prednisone
Интернет-магазин https://www…
Интернет-магазин https://www.minds.com/group/1969786005129007104/latest лицензионного софта и цифровых товаров предлагает широкий выбор программ для работы, бизнеса и дома. Покупайте официальные лицензии, антивирусы, офисные приложения и цифровые продукты по доступным ценам.
Онлайн-журнал https:/…
Онлайн-журнал https://profile.google.com/@tour.out о luxury travel и путешествиях со вкусом. Узнавайте о лучших отелях, частных виллах, яхтинге, авиации, гастрономических маршрутах и wellness-курортах. Вдохновляйтесь идеями для незабываемого отдыха.
Napdoku: Cozy Brain Puzzle…
Napdoku: Cozy Brain Puzzle http://play.google.com/store/apps/details?id=com.napdoku.puzzle is a relaxing logic game designed for brain training and unwinding. Solve number puzzles to sharpen your attention, concentration, and logical thinking skills as you progress through increasingly challenging levels.
Napdoku: Cozy Brain Puzzle…
Napdoku: Cozy Brain Puzzle https://play.google.com/store/apps/details?id=com.napdoku.puzzle is a relaxing logic game designed for brain training and unwinding. Solve number puzzles to sharpen your attention, concentration, and logical thinking skills as you progress through increasingly challenging levels.
Want to download Angry Birds…
Want to download Angry Birds الطيور الغاضبة for your smartphone or tablet? Check out this popular arcade game—launch birds from a slingshot, demolish structures, and beat engaging levels. Learn about the different versions of the game and how to install them.
Ищете, где получить получить…
Ищете, где получить получить сертификат ГОСТ Р ИСО 9001? Мы поможем организовать процесс сертификации, разобраться в требованиях стандарта, подготовить необходимые документы и пройти оценку системы менеджмента качества.
Want to download Angry Birds…
Want to download Angry Birds 愤怒的小鸟 for your smartphone or tablet? Check out this popular arcade game—launch birds from a slingshot, demolish structures, and beat engaging levels. Learn about the different versions of the game and how to install them.
Ищете, где получить получить…
Ищете, где получить получить сертификат ISO 9001? Мы поможем организовать процесс сертификации, разобраться в требованиях стандарта, подготовить необходимые документы и пройти оценку системы менеджмента качества.
provigil: provigil - buy…
provigil: provigil - buy modvigil no prescription
https://getsynapsefuel.xyz/#…
https://getsynapsefuel.xyz/# Get Synapse Fuel
Получите оформить сертификат…
Получите оформить сертификат ISO 9001 с профессиональной поддержкой специалистов. Подберем подходящую схему сертификации, проконсультируем по требованиям стандарта, подготовим необходимые документы и рассчитаем стоимость услуг.
Нужны ворота? автоматические…
Нужны ворота? автоматические ворота для гаража для дома, гаража или коммерческого объекта. Поможем выбрать конструкцию, материалы и систему открывания, подготовим индивидуальный проект и организуем установку под ключ.
Нужен забор? https://www…
Нужен забор? https://www.zabor-dlya-dachi-evroshtaketnik-metallicheskiy.ru/uslugi/za… для участков любой площади. Предлагаем широкий выбор конструкций, материалов и вариантов оформления. Изготовим ограждение по индивидуальному проекту, согласуем цену и выполним установку на вашем участке.
Компания FarbWood https:/…
Компания FarbWood https://farbwood.by предлагает пиломатериалы из сибирской лиственницы для частного и коммерческого строительства в Минске и по всей территории Беларусь.
Сервисная поддержка сайтов…
Сервисная поддержка сайтов https://servisnaya-podderzhka.ru профессиональная помощь в обслуживании, обновлении и доработке веб-ресурсов. Закажите технические работы, исправление ошибок, настройку функционала, оптимизацию и сопровождение сайта.
Нужен забор? забор из…
Нужен забор? забор из штакетника металлического со столбами для участков любой площади. Предлагаем широкий выбор конструкций, материалов и вариантов оформления. Изготовим ограждение по индивидуальному проекту, согласуем цену и выполним установку на вашем участке.
Нужны ворота? узнать здесь…
Нужны ворота? узнать здесь для дома, гаража или коммерческого объекта. Поможем выбрать конструкцию, материалы и систему открывания, подготовим индивидуальный проект и организуем установку под ключ.
Сервисная поддержка сайтов…
Сервисная поддержка сайтов https://servisnaya-podderzhka.ru профессиональная помощь в обслуживании, обновлении и доработке веб-ресурсов. Закажите технические работы, исправление ошибок, настройку функционала, оптимизацию и сопровождение сайта.
medicine amoxicillin 500mg:…
medicine amoxicillin 500mg: AmoxiSprint - amoxicillin buy no prescription
Слышал витражи по технике…
Слышал витражи по технике фьюзинг будто это просто склеенные кусочки. На самом деле стекло спекают в печи при 750–850°С, и важно, чтобы коэффициенты температурного расширения совпадали. Подробности процесса и разновидности спекания есть на странице.
Замечено: оформление шарами…
Замечено: оформление шарами детского праздника. Родители часто выбирают фигуры из шаров и акции для мальчиков и девочек. На странице есть и отдельные шары с гелием — удобно, если нужен небольшой акцент, а не целая композиция.
Заметила: мебель от…
Заметила: мебель от производителя. В обсуждениях часто хвалят местных производителей за возможность подогнать мебель под нишу или нестандартную планировку. На bigmebel-komsomolsk.ru представлены кухни, шкафы-купе и гардеробные, которые можно заказать по своим размерам.
Перед решением: фундамент…
Перед решением: фундамент каркасный дом. На странице описан порядок работ: разметка траншеи, бурение скважин, арматурный каркас и бетонирование. Проверьте, учтены ли в вашем проекте гидроизоляция и утепление. Это поможет избежать переделок.
GetSynapseFuel: order…
GetSynapseFuel: order modalert 200mg online - order modalert 200mg online
http://getsynapsefuel.com/#…
http://getsynapsefuel.com/# modafinil
https://getsynapsefuel.xyz/#…
https://getsynapsefuel.xyz/# order modalert 200mg online
Сравнение цветы в лимассол…
Сравнение цветы в лимассол на кипре двух вариантов: готовый букет или корзинка. Корзинки из роз, лилий, гербер, ирисов, тюльпанов и хризантем выглядят устойчивее и дольше стоят. Выбирайте по поводу и получателю, а перед заказом уточните город и пожелания.
Узнать подробности прямо…
Узнать подробности прямо сейчас: https://skrovli.ru
Перейти к первоисточнику:…
Перейти к первоисточнику: https://skrovli.ru
provigil: buy modafinil…
provigil: buy modafinil online - Get Synapse Fuel
где займы на карту срочно…
где займы на карту срочно займ на карту история плохая
взять займ на карту…
взять займ на карту процентов заем на кредитную карту срочно
удобная ии фотосессия онлайн…
удобная ии фотосессия онлайн помогает создавать профессиональные фотографии прямо с телефона или компьютера. загружайте исходные снимки, выбирайте подходящие стили и получайте уникальные портреты для социальных сетей, работы и личного архива.
Самое интересное: https:/…
Самое интересное: https://shtukatur-stroy.ru
Проектирование сетевой…
Проектирование сетевой инфраструктуры https://network-serv.ru для офисов, предприятий и коммерческих объектов. Разрабатываем схемы локальных сетей, подбираем оборудование, рассчитываем нагрузку и обеспечиваем надежную основу для стабильной работы IT-систем.
Проектирование сетевой…
Проектирование сетевой инфраструктуры https://network-serv.ru для офисов, предприятий и коммерческих объектов. Разрабатываем схемы локальных сетей, подбираем оборудование, рассчитываем нагрузку и обеспечиваем надежную основу для стабильной работы IT-систем.
Квартиры в ЖК https:/…
Квартиры в ЖК https://kvartiralisino.ru от застройщика с удобными планировками и современными условиями проживания. Выбирайте подходящую недвижимость, сравнивайте площадь, стоимость и расположение, изучайте доступные варианты покупки.
онлайн займ на карту без…
онлайн займ на карту без истории займы онлайн лучшие на карту
40 mg prednisone pill and…
40 mg prednisone pill and prednisone 20mg online where can i buy prednisone without prescription
http://www.e-tsuyama.com/cgi-bin/jump.cgi?jumpto=https://corticalmsuppl… prednisone 54899 or http://www.1gmoli.com/home.php?mod=space&uid=1366304 prednisone 500 mg tablet
order prednisone 100g online without prescription where can i get prednisone over the counter and prednisone 20mg capsule prednisone 2 mg
cheap amoxicillin 500mg and…
cheap amoxicillin 500mg and cost of amoxicillin prescription generic amoxicillin
http://urlaubhamster.de/out.php?link=http://getsynapsefuel.com amoxicillin 500 mg for sale and https://brueckrachdorf.de/user/ssxreymvzh/ amoxicillin online canada
buy amoxicillin online cheap can i purchase amoxicillin online or amoxicillin 500mg no prescription can you buy amoxicillin over the counter canada
http://amoxisprintmeds.com/#…
http://amoxisprintmeds.com/# price for amoxicillin 875 mg
buy prednisone online uk:…
buy prednisone online uk: prednisone 10mg fast delivery - prednisone medication
provigil: Get Synapse Fuel -…
provigil: Get Synapse Fuel - Get Synapse Fuel
https://getsynapsefuel.xyz/#…
https://getsynapsefuel.xyz/# modafinil
Pagination
Add new comment