umbraco / UmbracoDocs

The official Umbraco Documentation
https://docs.umbraco.com
MIT License
266 stars 770 forks source link

Checking a Rich Text Editor for a value or not #5692

Closed marcemarc closed 9 months ago

marcemarc commented 9 months ago

What type of issue is it? (Choose one - delete the others)

Discussion Wrong documentation

What article/section is this about?

(link here)

Describe the issue

When you use a RichTextEditor for a property in an Umbraco Document Type, when you come to write that value out in a template you can use

@(Model.Value<IHtmlString>("richText")) or with modelsbuilder @Model.RichText

Now you might have some other 'markup' around the richtext, perhaps a hardcode heading or just some wrapping <div s or <aside etc etc

Now you might not want to render that supporting 'markup and content' if there is nothing entered into the Rich Text Editor field in Umbraco.

Historically Umbraco has provided a HasValue("richText") helper method - and what this does is check whether the RTE is empty - AND ALSO CRUCIALLY ignores any empty html elements.

So if your Rich Text Editor has <p> </p> in it HasValue("bodyText") would be False (it uses HtmlAgilityPack underneath to check for empty html)

However, in your WithModelsbuilder example in the document above you suggest the Modelsbuilder 'equivalent' to HasValue is to have if (!string.IsNullOrEmpty(Model.RichText.ToString())) but that isn't the same! if the RTE has<p> </p> empty tag this code would return True, whereas HasValue would be more usefully False...

(Also if RichText is Null for any reason it will blow up on the ToString() before you get to the Null or empty check!)

sooooo Would the equivalent for Modelsbuilder actually be?

var richTextPropertyType = MyClassName.GetModelPropertyType(d => d.RichText);
if (Model.HasValue(richTextPropertyType.PropertyTypeAlias)){

That way you have all the goodness and unit tests around HasValue against an RTE, but with all the strongly typing of modelsbuilder that everyone knows and loves?

(or is there an easier way to get the Property Alias via Modelsbuilder these days?)

regards

Marc

marcemarc commented 9 months ago

no I think I dreamed it, thought HasValue cleaned things up but I don't think it does now... a moment of madness