I’m using Contentful migrations, and I’m looking for a way to convert a Long Text field to a Rich Text field.
e.g. from this:
MyModel
* title - Short Text
* description - Long Text
to this:
My Model
* title - Short Text
* description - Rich Text
I expect the steps to be:
- Create new field,
descriptionRichText
- Copy the current contents of
description
to descriptionRichText
- NB: I understand that Long Texts are actually Markdown, but in my case they’re just plain strings, so I’m sure I even need to parse here
- Delete
description
- Rename
descriptionRichText
to description
However, I’m having trouble figuring out how to do this. There’s a guide about migrating to rich text here, but it’s waaaay more complicated than my case (the post details merging a field consisting of multiple linked entries of different types into a rich text field), and I can’t figure out how to apply the code given there to my use case.
Any assistance would be appreciated.
NB: this is essentially the same question as this post - I even pinched the title - but that post is locked, and has no answers, anyway.
The rich text field is fundamentally different from the long (markdown) text field, as the rich text field is fully JSON based as opposed to the simple text that comes from a markdown field. If you’re not using images or any other fancy stuff, then you can use the basic usage example from https://www.npmjs.com/package/@contentful/rich-text-from-markdown.
If you really want something more simple and not use the tool, then you could try to create the JSON object yourself with a document node and an embedded paragraph node. And then just use the text from your description field as a the value for the embedded node.
Something like this:
const richTextDocument = {
nodeType: 'document',
data: {},
content: [
{
nodeType: 'paragraph',
content: [
{
nodeType: 'text',
marks: [],
value: '<YOUR TEXT>',
data: {}
}
],
data: {}
}
]
};
Hi @kah.tang,
That was pretty much the solution I came to, as well. I just kept it simple and created the Rich Text hash manually, though of course the gem would do that too.
Via the example in the CLI docs, I used .transformEntries
.
Here’s how my migration looked in the end:
module.exports = function(migration) {
migration.transformEntries({
contentType: 'myModel',
from: ['description'],
to: ['descriptionRichText'],
transformEntryForLocale: function (fromFields, currentLocale) {
if (fromFields.description === undefined) {
return;
}
if (currentLocale === 'mi') {
return;
}
if (fromFields.description['en-NZ'] !== undefined) {
const description = fromFields.description['en-NZ'];
const richTextDescription = {
"nodeType": "document",
"data": {},
"content": [
{
"nodeType": "paragraph",
"data": {},
"content": [
{
"data": {},
"marks": [],
"value": description,
"nodeType": "text"
}
]
}
]
};
return { descriptionRichText: richTextDescription };
}
}
});
}
Hopefully that’s helpful to someone!
4 Likes