gotohayato.com

月(ダークモード)
太陽(ライトモード)

Drupal 7: How to disable a content type

Drupal 7

While developing a site with Drupal, at times I’d like to disable a content type without removing it. I just want to disable one.

The database table where content types are stored is node_type. And there’s a column disabled in it. We can disabled a content type by changing the column value to 1.

There are APIs for that. We can use node_type_load() and node_type_save() to do it.

<?php
// Disable a content type named 'article'.
$name = 'article';
$type_info = node_type_load($name);
$type_info->disabled = 1;
node_type_save($type_info);

We can disable a content type easily but re-enabling them is a little tricky. We cannot use node_type_load() for disabled content types and should use db_select() directly.

Here’s a sample module only to disable a content type.

<?php
/**
* @file
* A module which disable the default Article content.
*/
/**
* Implements hook_install().
*/
function default_disabler_install() {
// Disable the article content type.
_default_disabler_disable_node_type('article');
}
/**
* Implements hook_install().
*/
function default_disabler_uninstall() {
// Re-enable the article content type.
_default_disabler_enable_node_type('article');
}
/**
* Disable a content type.
*
* @param string $name
* Content type name (machine name).
*/
function _default_disabler_disable_node_type($name) {
$type_info = node_type_load($name);
if ($type_info) {
$type_info->disabled = 1;
node_type_save($type_info);
watchdog('default_disabler', 'Node type @name is disabled.', [
'@name' => $name,
], WATCHDOG_WARNING);
}
else {
watchdog('default_disabler', 'Node type @name is not found and couldn\'t be disabled.', [
'@name' => $name,
], WATCHDOG_WARNING);
}
}
/**
* Re-enable a disabled content type.
*
* @param string $name
* Content type name (machine name).
*/
function _default_disabler_enable_node_type($name) {
// Since node_type_load() cannot be used for disabled content types,
// a low-level function db_select() is used here.
// Re-enable a content type if it's disabled.
$query = db_select('node_type', 'nt')
->fields('nt', array('disabled'))
->condition('type', $name);
$disabled = $query->execute()->fetchAssoc();
if (!empty($disabled['disabled'])) {
$query = db_update('node_type')
->fields(array('disabled' => 0))
->condition('type', $name);
$result = $query->execute();
if ($result) {
watchdog('default_disabler', 'Node type @name is enabled.', [
'@name' => $name,
], WATCHDOG_WARNING);
}
}
else {
watchdog('default_disabler', 'Node type @name is not found and couldn\'t be enabled.', [
'@name' => $name,
], WATCHDOG_WARNING);
}
}

参考


後藤隼人
ウェブサイト制作・ウェブアプリ開発やマーケティングをしています。
GitHub

お知らせ

大阪大学医学部附属病院さんで現在クラウドファンディングのプロジェクトをされています(後藤も少しだけ寄附させていただきました)。
© 2020 gotohayato.com
サイトについてタグアーカイブメッセージを送る