J Cane
J Cane

Reputation: 1

Drupal 8 hook_update_n code example needed

We have an existing custom module for our Drupal 8 application that created a content type and a view. The "news" module is in our production environment running fine; many pieces of content have been created using it.

Now enhancements have been requested: 2 new fields and a change to the view. I have made the changes using the admin UI in our dev environment, but I will need to put these changes into the module's code for version control so that in new site instances, one need not remember to make UI changes after installing the module.

The fields:
field_show_on_page, Field Type: List (text)
field_news_dateline, Field Type: Date
View:
The change in the view is on what field the sorting is done.

It would be simple to export the fields and view configurations and add them to the module>config >install folder, but for the change to be picked up, that requires uninstalling and reinstalling the module, which can't be done without needing to delete news content, which is not acceptable.

I understand the changes can be done in hook_update_N in the news.install file. But I cannot find examples for this function that is close enough for this need. I understand the function should be written as:

news_update_8001() {}
but what would go in the body to add the two fields and update the view?

Thank you.

Upvotes: 0

Views: 1109

Answers (1)

soirederf
soirederf

Reputation: 130

If you have the new fields in your config you can just delete the old fields by adding this in your hook and then run drush updb before you import the config:

$field = \Drupal::entityTypeManager()->getStorage('field_config')->load('node.news.old_field');
if ($field) {
    $field->delete();
}

Upvotes: 0

Related Questions