10

With Drupal 7 we had the Field Rename module, but this has not yet been ported to Drupal.

So what SQL magic is needed to rename a field in Drupal 8?

3
  • 1
    You probably won't get too far with raw SQL (but you wouldn't have in Drupal 7 either). Field storage (which includes the name) and relationship to entity types/bundles, are stored in serialised PHP strings. Using the API would be best
    – Clive
    Commented Nov 24, 2017 at 13:10
  • Thank you Clive. I'm not up to speed with PHP or the API and wouldn't know where to start I'm afraid Commented Nov 24, 2017 at 15:16
  • You can do this with drush or drupal console and drupal Configuration management, just export your site configuration, edit what you need and import same then.
    – StevanRS
    Commented Nov 30, 2017 at 17:32

2 Answers 2

24

I've had the misfortune to need to do this before :P , and my advice would be as follows:

Forget about renaming the existing field; the machine name is scattered across several different hard-to-edit places, and you'll probably miss some and get weird errors. For example, if you just rename the tables and the configuration, the field API will throw a fit when it tries to delete the old tables and finds they're already gone. The schema information is kept in the keyvalue store, and cannot be rebuilt from scratch, so if you make manual changes it's easy to end up in a broken state.

Instead, recreate the field with the correct machine name, then copy over the data with SQL, and finally delete the old field.

INSERT INTO node__field_new SELECT * FROM node__field_old;
INSERT INTO node_revision__field_new SELECT * FROM node_revision__field_old;
2
  • This sounds good advice. I'll give it a try and report back. Thanks Commented Nov 24, 2017 at 18:22
  • 5
    Ta Dah! This was simple and trouble free. Thank you for the tip. Commented Nov 25, 2017 at 13:40
1

Regarding the latest comment from StevanRS, its not simply than that, because if you just import after renaming, it will fail because original field will not exist anymore. So, here is my proposal:

  • Export the config. Save apart all those files with some config for the field. *
  • Delete that field on drupal UI.
  • Export config again (with field already removed)
  • Copy renamed files again on config folder.
  • Then you can import properly :)

Tipical files you need to save:

  • field.field.yourentity.yourfield
  • field.storage.yourentity.yourfield
  • core.entity_form_display.yourentity.yourfield
  • core.entity_view_display.yourentity.yourfield

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.