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://skrovli.ru
займы без кредитной истории…
займы без кредитной истории на карту срочно займ на карту мфо
http://corticalmsupply.com/#…
http://corticalmsupply.com/# buying prednisone mexico
займ на карту первый раз…
займ на карту первый раз взять займ на карту
современная женская…
современная женская фотосессия ии помогает создавать разнообразные портреты с помощью искусственного интеллекта. выбирайте стиль съемки, меняйте виртуальный фон и подбирайте образы для получения эффектных фотографий без посещения фотостудии.
Переходите по ссылке: https:…
Переходите по ссылке: https://shtukatur-stroy.ru
взять займ на карту без…
взять займ на карту без отказа займ на карту без проверки истории
Открыть полную публикацию:…
Открыть полную публикацию: https://aspa-stroy.ru
Самое важное сегодня: https:…
Самое важное сегодня: https://shtukatur-stroy.ru
Новое в категории: https:/…
Новое в категории: https://shtukatur-stroy.ru
Изучить подробности: https:/…
Изучить подробности: https://aspa-stroy.ru
доступная ии фотосессия по…
доступная ии фотосессия по фото онлайн позволяет получить красивые изображения без аренды студии и услуг фотографа. загрузите фотографию, выберите понравившийся образ и создайте серию уникальных снимков с помощью искусственного интеллекта.
просто создать фотосессию с…
просто создать фотосессию с помощью ии, используя собственные фотографии и современные нейросети. подбирайте образы, экспериментируйте с освещением и виртуальными локациями, получайте оригинальные изображения для личного архива и социальных сетей.
персональная ии фотосессия…
персональная ии фотосессия для мужчины позволяет создавать выразительные портреты для работы, личного бренда и социальных сетей. подбирайте деловой или повседневный стиль, меняйте фон и получайте новые фотографии с помощью нейросети.
разнообразные мужские…
разнообразные мужские фотосессии ии позволяют подобрать индивидуальный стиль для любых целей. создавайте деловые портреты, фотографии в повседневной одежде и fashion-образы, экспериментируя с фоном и виртуальными декорациями.
персональная ии фотосессия…
персональная ии фотосессия для мужчины позволяет создавать выразительные портреты для работы, личного бренда и социальных сетей. подбирайте деловой или повседневный стиль, меняйте фон и получайте новые фотографии с помощью нейросети.
инновационная ии фотосессия…
инновационная ии фотосессия нейросеть позволяет преобразовывать исходные снимки в разнообразные визуальные образы. создавайте портреты, деловые фотографии и тематические композиции, подбирая оформление под свои предпочтения.
Усі свіжі новини змієва…
Усі свіжі новини змієва зібрані на міському сайті на Харківщині. Події, заходи та корисна інформація для мешканців.
Town news from https://zmiiv…
Town news from https://zmiiv.com.ua, a local website in Zmiiv, Kharkiv region, Ukraine. It covers events and useful information for residents.
prednisone 2 mg or…
prednisone 2 mg or prednisone canada pharmacy prednisone 10mg for sale
https://images.google.sm/url?q=https://corticalmsupply.com prednisone 12 tablets price and http://www.sportchap.ru/user/idgimuknzt/ prednisone 5mg coupon
where can i buy prednisone without prescription price of prednisone 5mg or no prescription prednisone canadian pharmacy prednisone for sale
amoxicillin 800 mg price or…
amoxicillin 800 mg price or amoxicillin 250 mg capsule how to get amoxicillin
https://www.google.com.sa/url?q=https://getsynapsefuel.com amoxicillin 500 mg price or http://la-maison-des-amis.com/user/ssjmqfajhb/ ampicillin amoxicillin
amoxicillin cost australia amoxicillin canada price or buy amoxicillin canada order amoxicillin online
SertraCalmRx: buy zoloft…
SertraCalmRx: buy zoloft online - order sertraline 50m
order sertraline 50m: zoloft…
order sertraline 50m: zoloft - SertraCalmRx
Новости Ивано-Франковска…
Новости Ивано-Франковска публикует https://mycity.if.ua, сайт города и Прикарпатья. События, происшествия, культура и полезные материалы для жителей.
City news from https://24…
City news from https://24.lutsk.ua, a local website in Lutsk, Volyn region, Ukraine. It covers daily events and transport updates.
Новини Івано-Франківська…
Новини Івано-Франківська публікує https://mycity.if.ua, сайт міста та Прикарпаття. Події, культура й корисні матеріали для мешканців.
http://lisinoguarddirect.com…
http://lisinoguarddirect.com/# lisinopril 20mg india
http://sertracalmrx.com/#…
http://sertracalmrx.com/# SertraCalm
cheap sertraline 100mg…
cheap sertraline 100mg tablets: SertraCalm - buy zoloft online
Сериал https://breakingbed…
Сериал https://breakingbed.org — захватывающая криминальная драма о школьном учителе химии, который решает изменить свою жизнь после серьезного диагноза. Узнайте подробности сюжета, познакомьтесь с героями и изучите все сезоны.
Сериал https://vampirediares…
Сериал https://vampirediares.info — мистическая история о любви, дружбе и противостоянии сверхъестественных сил. Следите за судьбой Елены Гилберт и братьев Сальваторе, знакомьтесь с персонажами и изучайте все сезоны популярной вампирской саги.
https://sertracalmrx.com/#…
https://sertracalmrx.com/# buy zoloft online
cost generic clomid without…
cost generic clomid without a prescription ClomiPulseRx how to get generic clomid without dr prescription
where buy generic clomid…
where buy generic clomid price: ClomiPulse - can i get clomid no prescription
Как выбрать квартиру https:/…
Как выбрать квартиру https://kvartiranovostroi.ru в новостройке? Сравнивайте варианты недвижимости, оценивайте планировки, инфраструктуру жилых комплексов и особенности новых домов. Полезные материалы помогут разобраться в основных критериях выбора.
Ищете квартиру https:/…
Ищете квартиру https://novostroyki-spb78.ru в новостройке СПб? Знакомьтесь с жилыми комплексами Санкт-Петербурга, изучайте предложения застройщиков, доступные метражи, планировки и особенности новых районов.
Выбирайте недвижимость https…
Выбирайте недвижимость https://kvartira-novostroyka2.ru осознанно: изучайте проекты новых домов, сравнивайте квартиры по стоимости и характеристикам, обращайте внимание на благоустройство территории и транспортную доступность жилых комплексов.
Современные новостройки…
Современные новостройки https://noviydomstroika.ru предлагают разные варианты жилья для семей, молодых специалистов и инвесторов. Изучайте особенности жилых комплексов, сравнивайте цены, расположение и доступные планировки квартир.
Выбирайте недвижимость https…
Выбирайте недвижимость https://kvartira-novostroyka2.ru осознанно: изучайте проекты новых домов, сравнивайте квартиры по стоимости и характеристикам, обращайте внимание на благоустройство территории и транспортную доступность жилых комплексов.
https://lisinoguarddirect…
https://lisinoguarddirect.xyz/# lisinopril 15 mg
Как выбрать квартиру https:/…
Как выбрать квартиру https://kvartiranovostroi.ru в новостройке? Сравнивайте варианты недвижимости, оценивайте планировки, инфраструктуру жилых комплексов и особенности новых домов. Полезные материалы помогут разобраться в основных критериях выбора.
Срочно нужны деньги? займ на…
Срочно нужны деньги? займ на карту без процентов 30 дней удобный способ получить денежные средства дистанционно. Узнайте, какие условия предлагают микрофинансовые организации, какие документы необходимы для оформления и на что обратить внимание при выборе займа.
Как выбрать квартиру https:/…
Как выбрать квартиру https://kvartiranovostroi.ru в новостройке? Сравнивайте варианты недвижимости, оценивайте планировки, инфраструктуру жилых комплексов и особенности новых домов. Полезные материалы помогут разобраться в основных критериях выбора.
lisinopril 20 mg over the…
lisinopril 20 mg over the counter: buy lisinopril online - lisinopril 20 pills
cura?atorie chimica mobila…
cura?atorie chimica mobila cura?are chimica a mobilierului tapi?at
If you’re considering e…
If you’re considering e-Residency, majanduskonverents explains what the digital status changes and which decisions still belong in your business plan.
curatarea tapiteriei textile…
curatarea tapiteriei textile curatare mobila moale
zoloft SertraCalmRx Sertra…
zoloft SertraCalmRx Sertra Calm Rx
If you’re considering e…
If you’re considering e-Residency, majanduskonverents explains what the digital status changes and which decisions still belong in your business plan.
https://clomipulserx.xyz/#…
https://clomipulserx.xyz/# how to buy clomid without a prescription
Pagination
Add new comment