Drupal - How to rename column of a content type

April 27, 2020

Introduction

You already have a content type with one or more fields in it. Later, you realize you should rename it due to whatever reason. Lets take an example:

  • A text field(long text area)
  • Image field

Drupal provides no way to rename existing fields of a content type. But, you can do this programatically or by a db query.

Programmatic Solution

Do following steps:

  • Add the fields into your content type, with the name you want
  • See below php code for drupal
$query = db_select( 'node', 'n' );
  $query
    ->condition( 'n.type', 'article' )
    ->fields('n', array('nid'));
  $result = $query
     ->execute()
   ->fetchAll();

  foreach( $result as $row ) {
    $nd = Drupal\node\Entity\Node::load($row->nid);
  
    $nd->body = $nd->field_article_introduction;
    $nd->field_image = $nd->field_top_image;
    $nd->save();
  }

The idea is to fetch all such nodes for that particular content type, and assign old values to the new fields you just created.

  • You can put multiple fields if you have in the php code above.
  • Make sure you have copied content, by loading one or two nodes
  • Find out all the views you have created wiht old fields. You need to put new fields with same settings.
  • Find out the occurrences of those old fields in your custom theme code.
  • Now, delete old fields from your content type

Clear the cache and test it.


Similar Posts

Latest Posts