Thursday, 30 March 2023

Sitecore Forms - Markdown in Text Field

Update 30/03/2023: Bonus, now with added bold and line breaks!


One of the main limitations of Sitecore Forms in my opinion is not having a rich text field. No doubt this is something that could be implemented without too much of a headache, but a simpler option is to allow basic markdown such as links.

eg. this is a sentence with [a link](https://google.com) in it

Fortunately, using a custom field factory (see my previous post) this is pretty simple!

CustomFieldFactory.setComponent(AllFieldTypes.TextField, (props : FieldWithValueProps<FormField<TextViewModel>>) => {
// Replace markdown style links in text, eg. this is a sentence with [a link](https://google.com) in it
const markdownRegex = /\[([^\]]+)\]\(([^\)]+)\)/;
props.field.model.text = props.field.model.text?.replaceAll('\n','<br/>');
props.field.model.text = props.field.model.text?.replace(/\*\*(.*?)\*\*/g, "<b>$1</b>");
if(props.field.model.text && props.field.model.text.match(markdownRegex)){
props.field.model.text = props.field.model.text.replace(markdownRegex, '<a href="$2">$1</a>');
const Tag = (props.field.model.htmlTag || 'p');
return React.createElement(Tag, { className: props.field.model.cssClass, dangerouslySetInnerHTML: {__html: props.field.model.text} });
}
return TextField(props);
});

No comments:

Post a Comment