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
https://sertracalmrx.xyz/#…
https://sertracalmrx.xyz/# SertraCalm
https://clomipulserx.xyz/#…
https://clomipulserx.xyz/# can you buy generic clomid pills
where can i get generic…
where can i get generic clomid without rx: clomiphene citrate tablets online - buying generic clomid prices
Наблюдение: отделка коттеджа…
Наблюдение: отделка коттеджа специалистами. Специалисты с многолетним опытом отделки разного класса помогают избежать ошибок. На странице описаны наружные и внутренние работы, включая подбор материалов. Перед заказом уточните, какие материалы использовались на похожих объектах.
Смотрите аренда самосвала по…
Смотрите аренда самосвала по тарифам прежде всего на тип груза и модель: на странице предлагают КамАЗ, ЗИЛ и HOWO. Эти машины берут песок, щебень, керамзит, а также строительный мусор и снег. Тариф зависит от объёма и расстояния — уточняйте у исполнителя.
Мультсериал Симпсоны https:/…
Мультсериал Симпсоны https://simpsonsfun.ru смотреть онлайн — отличная возможность окунуться в забавную жизнь семьи из Спрингфилда. Следите за приключениями Гомера, Мардж, Барта, Лизы и Мэгги, вспоминайте любимые эпизоды и знакомьтесь с новыми сериями.
Сериал Остаться в живых…
Сериал Остаться в живых остаться в живых смотреть переносит зрителей на таинственный остров, где выжившие после авиакатастрофы пытаются найти способ спастись. Смотрите все сезоны, следите за развитием событий и раскрывайте секреты главных героев.
generic clomid without dr…
generic clomid without dr prescription: order clomid without prescription - clomid cost
http://clomipulserx.com/#…
http://clomipulserx.com/# generic clomid without insurance
how to buy clomid without a…
how to buy clomid without a prescription or get cheap clomid for sale get clomid
https://cs.eservicecorp.ca/eService/sr/Login.jsp?fromSearchTool=true&fr… buy clomid without prescription and http://www.orangepi.org/orangepibbsen/home.php?mod=space&uid=7285376 buy generic clomid without insurance
cost of clomid can you buy clomid prices and where can i get cheap clomid without dr prescription can you buy generic clomid without a prescription
lisinopril 80 mg tablet:…
lisinopril 80 mg tablet: generic zestril no rx - zestril coupon
Сериал Секретные материалы…
Сериал Секретные материалы https://x-files.my — культовая фантастическая история о загадочных явлениях, необъяснимых событиях и расследованиях ФБР. Следите за работой агентов Малдера и Скалли, изучайте сезоны и открывайте тайны, скрытые от обычных людей.
Мультсериал Гравити Фолз…
Мультсериал Гравити Фолз https://gravity-falls.ru — отличная возможность отправиться в загадочный городок вместе с близнецами Диппером и Мэйбл. Вас ждут необычные существа, мистические тайны, забавные приключения и увлекательные расследования.
how can i get clomid price:…
how can i get clomid price: ClomiPulseRx - where to buy cheap clomid
Сериал Сверхъестественное…
Сериал Сверхъестественное https://tv-supernatural.ru — возможность погрузиться в мир мистики, демонов и необъяснимых событий. Следите за приключениями братьев Сэма и Дина Винчестеров, изучайте все сезоны и знакомьтесь с их опасными расследованиями.
zoloft or buy zoloft online…
zoloft or buy zoloft online cheap sertraline 100mg tablets
https://www.google.ad/url?sa=t&url=https://sertracalmrx.com buy zoloft onlineand https://forum.panabit.com/home.php?mod=space&uid=673720 SertraCalmRx
cheap sertraline 100mg tablets SertraCalmRxand cheap sertraline 100mg tablets Sertra Calm Rx
https://clomipulserx.com/#…
https://clomipulserx.com/# buying generic clomid without dr prescription
Смотрите историю Патрика…
Смотрите историю Патрика Джейна https://mentalist.my человека, способного замечать мельчайшие детали и раскрывать чужие секреты. В сериале «Менталист» каждое расследование превращается в интеллектуальную игру, где важны логика, психология и внимание к деталям.
I discovered SVG laser cut…
I discovered SVG laser cut files while looking for SVG templates for my laser. There are plenty of laser cut ideas to browse.
Увлекательные кулинарные…
Увлекательные кулинарные https://kulinarnyj-den-rozhdeniya.ru мастер-классы для яркого дня рождения и праздников: готовим вкусные блюда под руководством шефа, весело проводим время и создаём незабываемые эмоции!
Увлекательные кулинарные…
Увлекательные кулинарные https://kulinarnyj-den-rozhdeniya.ru мастер-классы для яркого дня рождения и праздников: готовим вкусные блюда под руководством шефа, весело проводим время и создаём незабываемые эмоции!
https://clomipulserx.com/#…
https://clomipulserx.com/# buying cheap clomid without dr prescription
order clomid without dr…
order clomid without dr prescription or get clomid no prescription cost generic clomid without a prescription
https://www.google.az/url?q=https://clomipulserx.com can i get cheap clomid without rx and https://cyl-sp.com/home.php?mod=space&uid=242742 can i get clomid without insurance
where can i buy cheap clomid without a prescription buying cheap clomid without dr prescription and where to get generic clomid price where buy clomid without a prescription
https://lisinoguarddirect…
https://lisinoguarddirect.com/# lisinopril 1 mg tablet
generic clomid without…
generic clomid without prescription: Clomi Pulse Rx - can you buy clomid without dr prescription
order clomid price and can i…
order clomid price and can i purchase clomid now where can i get generic clomid without prescription
https://images.google.com.kh/url?q=https://clomipulserx.com order cheap clomid now and http://ussher.org.uk/user/csndfiltko/?um_action=edit can i buy clomid
can i buy cheap clomid online where buy cheap clomid without insurance and buying generic clomid without insurance can i buy clomid without a prescription
lisinopril 10mg tablets…
lisinopril 10mg tablets price: buy lisinopril online - lisinopril 20mg for sale
https://sertracalmrx.com/#…
https://sertracalmrx.com/# SertraCalmRx
buy generic clomid without…
buy generic clomid without dr prescription: order clomid without prescription - order generic clomid prices
https://lisinoguarddirect…
https://lisinoguarddirect.com/# prinivil drug cost
where to buy ventolin…
where to buy ventolin AeroBreatheSupply can you buy ventolin over the counter nz
http://aerobreathesupply.com…
http://aerobreathesupply.com/# ventolin tablet 2 mg
http://aerobreathesupply.com…
http://aerobreathesupply.com/# ventolin online uk
zithromax capsules australia…
zithromax capsules australia: cheap azithromycin 500mg tablets - buy zithromax online with mastercard
generic zithromax medicine:…
generic zithromax medicine: Get Zithro Sprint - can i buy zithromax online
https://aerobreathesupply…
https://aerobreathesupply.xyz/# ventolin prices in canada
ivermectin 90 mg: ivermectin…
ivermectin 90 mg: ivermectin over the counter canada - ivermectin 3mg tablets
can you buy ventolin over…
can you buy ventolin over the counter uk: AeroBreathe - ventolin in usa
https://getzithrosprint.com/…
https://getzithrosprint.com/# zithromax 500 mg lowest price drugstore online
http://getzithrosprint.com/#…
http://getzithrosprint.com/# azithromycin zithromax
buy ventolin: salbutamol hfa…
buy ventolin: salbutamol hfa 100mcg buy - ventolin pharmacy
https://aerobreathesupply…
https://aerobreathesupply.xyz/# ventolin 4mg
https://iverbatchdirect.com/…
https://iverbatchdirect.com/# stromectol medication
order ventolin: ventolin 4mg…
order ventolin: ventolin 4mg - ventolin 6.7g
ivermectin uk: IverBatch -…
ivermectin uk: IverBatch - stromectol tablets
https://aerobreathesupply…
https://aerobreathesupply.com/# ventolin australia price
услуги по организации…
услуги по организации кейтеринга выездной кейтеринг
https://iverbatchdirect.com/…
https://iverbatchdirect.com/# where to buy ivermectin
услуги кейтеринга кейтеринг…
услуги кейтеринга кейтеринг сколько стоит
ivermectin 3: order generic…
ivermectin 3: order generic stromectol no rx - generic ivermectin cream
Pagination
Add new comment